import json

from django.contrib.contenttypes.fields import GenericRelation
from django.db import models

class TtStudentSet(models.Model):
    code = models.CharField(max_length=150)
    name = models.CharField(max_length=255)
    desc = models.TextField(null=True)
    department = models.ForeignKey("api.TtDepartment", on_delete=models.SET_NULL,null=True)
    academic_term = models.ForeignKey("api.TtAcademicTerm", on_delete=models.CASCADE)
    pos = models.ForeignKey("api.TtPos",on_delete=models.SET_NULL,null=True)
    planned_size = models.IntegerField(null=True)
    real_size = models.IntegerField(null=True)
    availability = models.ForeignKey("api.TtAvailability",on_delete=models.SET_NULL,null=True,blank=True,db_comment="NULL means custom")
    availability_pattern = models.TextField(null=True)
    start_preference = models.ForeignKey("api.TtStartPreference",on_delete=models.SET_NULL,null=True,blank=True,db_comment="NULL means custom")
    start_preference_pattern = models.TextField(null=True)
    usage_preference = models.ForeignKey("api.TtUsagePreference",on_delete=models.SET_NULL,null=True,blank=True,db_comment="NULL means custom")
    usage_preference_pattern = models.TextField(null=True)
    extra_data_1 = models.TextField(null=True)
    extra_data_2 = models.TextField(null=True)
    extra_data_3 = models.TextField(null=True)
    extra_data_4 = models.TextField(null=True)
    extra_data_5 = models.TextField(null=True)
    extra_data_6 = models.TextField(null=True)
    extra_data_7 = models.TextField(null=True)
    extra_data_8 = models.TextField(null=True)
    extra_data_9 = models.TextField(null=True)
    extra_data_10 = models.TextField(null=True)
    status = models.SmallIntegerField()
    created_by = models.BigIntegerField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_by = models.BigIntegerField(null=True)
    updated_at = models.DateTimeField(auto_now=True)

    # having this line wont add column in db, it make the function like TtStaff.avoid_concurrency.add() can be used
    module = models.ManyToManyField("api.TtModule",through="api.TtStudentSetModule")
    activity = models.ManyToManyField("api.TtActivity",through="api.TtStudentSetActivity")
    constraint_profile = models.ManyToManyField("api.TtConstraintProfile",through="api.TtStudentSetConstraintProfile")
    resource_map = models.ManyToManyField("api.TtWeek",through="api.TtStudentSetResourceMap")
    student = models.ManyToManyField("api.TtStudent",through="api.TtStudentSetStudent",related_name="student_set")


    # wont add column, just want create relation between staff and tt_tag_relation table
    tag = GenericRelation(
        "api.TtTagRelation",
        content_type_field="refer_table",
        object_id_field="refer_id",
    )

    STATUS_TO_CODE = {
        "active": 1,
        "inactive": 2,
    }

    IMPORT_RULES = {
        "code": ["required", "string", "unique"],
        "name": ["required", "string"],
        "desc": ["nullable", "string"],
        "department_id": ["nullable", "exist"], # department code
        "academic_term_id": ["nullable", "exist", {
            "required_if": {
                "field": "pos_id",
                "condition": "empty",
            }
        }], # academic term code, conditionally required: required when pos_id is empty
        "pos_id": ["nullable", "exist"], # pos code
        "planned_size": ["required", "integer"],
        "availability_id": ["nullable", "exist"], # availability code
        "availability_pattern": ["nullable", "string"],
        "start_preference_id": ["nullable", "exist"], # start_preference code
        "start_preference_pattern": ["nullable", "string"],
        "usage_preference_id": ["nullable", "exist"], # usage_preference code
        "usage_preference_pattern": ["nullable", "string"],
        **{
            f"extra_data_{i}": ["nullable", "string"]
            for i in range(1, 11)
        },
    }

    STUDENT_SET_MODULE = {
        "IMPORT_RULES": {
            "student_set_id": ["required", "string"], #student set code
            "module_id": ["required", "string"] # module code
        }
    }

    STUDENT_SET_ACTIVITY = {
        "IMPORT_RULES": {
            "student_set_id": ["required", "string"], #student set code
            "activity_id": ["required", "string"] # module code
        }
    }

    class Meta:
        db_table = "tt_student_set"

    def __str__(self):
        return self.name

    # @staticmethod
    # def get_student_set_by_pos_and_pos_module(pos_ids, pos_module_ids):
    #     student_sets = TtStudentSet.objects.filter(
    #         pos_id__in=pos_ids
    #     ).prefetch_related(
    #         "module__ttposmodulegroupmodule_set",
    #     )
    #     return_student_set = []
    #     for student_set in student_sets:
    #         get_student_set = True
    #         for module in student_set.module.all():
    #             for pos_module_relation in module.ttposmodulegroupmodule_set.all():
    #                 if pos_module_relation.id not in pos_module_ids:
    #                     get_student_set = False
    #         if get_student_set:
    #             return_student_set.append(student_set)
    #     return return_student_set
    @staticmethod
    def get_student_set_by_pos_and_pos_module(pos_ids, pos_module_ids):
        return (
            TtStudentSet.objects.filter(
                pos_id__in=pos_ids,
                # Filter student sets where the related module's bridge relation matches pos_module_ids
                module__ttposmodulegroupmodule__id__in=pos_module_ids,
            )
            .distinct()
        )
