from collections import defaultdict
from rest_framework import serializers, status

from api.models import TtStaffSuitability, TtDepartment, TtZone, TtAvailability, TtStartPreference, TtUsagePreference, \
    TtSuitability, TtTag, TtSetting, TtConstraintProfile
from api.models.tt_location import TtLocation
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator
from api.utils import calculate_default_period, decrypt_aes_128_cbc, encrypt_aes_128_cbc, log_critical_error, get_exception_detail
from rest_framework.exceptions import ValidationError
from api.translation import __


class LocationRules(AdminApiBase):
    def validate_request(self,request):
        rules = {
            "id": "nullable|array|exists:api.TtLocation,id",
        }
        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }
        # validate id first, cause need get location by id, if wrong id direct return error
        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)
        # custom error after basic validation

        if error:
            raise ValidationError(error)

    def post(self, request):
        # Validate input
        try:
            self.api_log_skip_outgoing_data=True
            self.validate_request(request)

            ids = request.data.get("id")
            if not ids:
                ids = []
            location = None
            if isinstance(ids, (list, tuple)) and len(ids) == 1:
                location = (
                    TtLocation.objects
                    .select_related("department", "zone", "availability", "start_preference", "usage_preference")
                    .prefetch_related(
                        "shared_with_department",  # 1
                        "suitability",  # 1
                        "constraint_profile",  # 1
                        "avoid_concurrency",  # 1
                        "tag__tag"
                        # tags means the relation add in models, __tag means the relation table tag_id get the tag object #2
                    )
                    .filter(id__in=ids)
                    .first()
                )

            info = None
            if location:
                info = {
                    "code": location.code,
                    "name": location.name,
                    "desc": location.desc,
                    "department_id": location.department_id,
                    "capacity": location.capacity,
                    "area": location.area,
                    "zone_id": location.zone_id,
                    "suitability": location.suitability.all().values_list("id",flat=True),
                    "avoid_concurrency": location.avoid_concurrency.all().values_list("id",flat=True),
                    "maximum_period": location.maximum_period,
                    "contract_period": location.contract_period,
                    "shared_with_department": location.shared_with_department.all().values_list("id",flat=True),
                    "shared_with_all_department": location.shared_with_all_department,
                    "availability_id": location.availability_id,
                    "availability_pattern": location.availability_pattern,
                    "usage_preference_id": location.usage_preference_id,
                    "usage_preference_pattern": location.usage_preference_pattern,
                    "start_preference_id": location.start_preference_id,
                    "start_preference_pattern": location.start_preference_pattern,
                    "tag": location.tag.all().values_list("tag_id",flat=True),
                }
                for i in range(1, 11):
                    extra_data_field = f"extra_data_{i}"
                    info[extra_data_field] = getattr(location, extra_data_field, None)

            models = {
                "department": (TtDepartment, ["id", "code", "name"]),
                "zone": (TtZone, ["id", "code", "name"]),
                "availability": (TtAvailability, ["id", "code", "name", "pattern"]),
                "start_preference": (TtStartPreference, ["id", "code", "name", "pattern"]),
                "usage_preference": (TtUsagePreference, ["id", "code", "name", "pattern"]),
                "suitability": (TtSuitability, ["id", "code", "name"]),
                "tag": (TtTag, ["id", "code", "name"]),
            }

            data = {}
            data['delete_confirmation_api'] = False
            data["allow_remove"] = [
                "desc",
                "department_id",
                "capacity",
                "area",
                "zone_id",
                "suitability",
                "maximum_period",
                "contract_period",
                "avoid_concurrency",
                "shared_with_department",
                "availability_id",
                "availability_pattern",
                "start_preference_id",
                "start_preference_pattern",
                "usage_preference_id",
                "usage_preference_pattern",
                "tag",
                *[f"extra_data_{i}" for i in range(1, 11)]
            ]
            for key, (model, fields) in models.items():
                data[key] = list(
                    model.objects.filter(status=model.STATUS_TO_CODE['active']).values(*fields)
                )

            # special case to handle avoid_concurrency, cause using different checking
            data["avoid_concurrency"] = list(
                TtLocation.objects.filter(status=TtLocation.STATUS_TO_CODE['active']).exclude(id__in=ids).values("id", "code", "name")
            )

            setting_params = {
                "minute_per_slot",
                "slot_per_day",
                "slot_per_week",
            }
            settings = TtSetting.get_multiple_setting(setting_params)
            data['based_setting'] = settings
            # 2026-01-29, since default start time and end time in academic_term is 9:00 to 19:00, so this default return 20(slot per day by default) * 6(mon to sat)
            # data['default_maximum_period'] = int(data["based_setting"]["slot_per_week"])
            # data['default_contract_period'] = int(data["based_setting"]["slot_per_week"])
            hours_per_week = TtLocation.WORK_TIME.get("hours_per_day") * TtLocation.WORK_TIME.get("days_per_week")
            default_period = calculate_default_period(hours_per_week, settings.get("minute_per_slot"))
            data['default_maximum_period'] = default_period
            data['default_contract_period'] = default_period
            data["constraint_profile"] = TtConstraintProfile.get_constraint_profile_rules()

            response = {
                "info": info,
                "rules": data,
            }

            return self.api_response(data=response)
        except ValidationError as e:
            first_message = e.detail['error']
            errors = e.detail['errors']
            return self.api_response(error=first_message,errors=errors,code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            e_details = get_exception_detail(e)
            log_critical_error(user_id=None,descr=e_details['descr'],url=e_details['url'],trace=e_details['trace'])
            return self.api_response(error=__("message.internal_server_error"),code=status.HTTP_500_INTERNAL_SERVER_ERROR)