import json

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

from api.translation import __


class TtConstraintProfile(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)
    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)

    free_block = models.ManyToManyField("api.TtFreeBlock",through="api.TtConstraintProfileFreeBlock")
    resource_break = models.ManyToManyField("api.TtResourceBreak", through="api.TtConstraintProfileResourceBreak")
    maximum_hour = models.ManyToManyField("api.TtMaximumHour", through="api.TtConstraintProfileMaximumHour")
    maximum_workspan = models.ManyToManyField("api.TtMaximumWorkspan", through="api.TtConstraintProfileMaximumWorkspan")
    travel_table = models.ManyToManyField("api.TtTravelTable", through="api.TtConstraintProfileTravelTable")

    tag = GenericRelation(
        "api.TtTagRelation",
        content_type_field="refer_table",
        object_id_field="refer_id",
    )

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

    class Meta:
        db_table = "tt_constraint_profile"

    def __str__(self):
        return self.name

    @staticmethod
    def get_constraint_profile_rules():
        return_data = []
        constraint_profile = (
            TtConstraintProfile.objects
            .prefetch_related(
                "free_block",
                "resource_break",
                "maximum_hour",
                "maximum_workspan",
                "travel_table"
                # tags means the relation add in models, __tag means the relation table tag_id get the tag object
            )
            .order_by("name")
        )
        relation_table = {
            "free_block": {"id", "code", "name"},
            "resource_break": {"id", "code", "name"},
            "maximum_workspan": {"id", "code", "name"},
            "maximum_hour": {"id", "code", "name"},
            "travel_table": {"id", "code", "name"}
        }

        for val in constraint_profile:
            constraint_profile_data = {}
            constraint_profile_data["id"] = val.id
            constraint_profile_data["code"] = val.code
            constraint_profile_data["name"] = val.name
            constraint_profile_data['active_constraints'] = []
            for relation_key, relation_columns in relation_table.items():
                relation_models = getattr(val, relation_key, None)
                if relation_models:
                    for item in relation_models.all():
                        constraint_profile_data["active_constraints"].append(item.name)

                        # constraint_profile_data["active_constraints"].append({
                        #     **{col: getattr(item, col) for col in relation_columns},
                        #     "category": relation_key,
                        #     "category_name": __("attr." + relation_key)
                        # })

            return_data.append(constraint_profile_data)
        return return_data