from rest_framework import status
from rest_framework.exceptions import ValidationError

from api.models import TtStaff, TtTagRelation, TtLocation
from api.translation import __
from api.utils import log_critical_error, get_exception_detail
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator

class LocationList(AdminApiBase):
    def validate_request(self,request):
        rules = {
            "filter": "nullable",
            "page": "nullable",
            "per_page": "nullable",
            "sort_by": "nullable",
            "order_by": "nullable",
        }
        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),e
        }
        # validate id first, cause need get pos by id, if wrong id direct return error
        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)


    def post(self, request):
        try:
            self.api_log_skip_outgoing_data=True
            self.validate_request(request)
            data = self.get_data(request)
            response = 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)

    def get_data(self,request):
        locations = (
            TtLocation.objects
            .select_related("department","zone","availability","start_preference","usage_preference")
            .prefetch_related(
                "shared_with_department",
                "suitability",
                "constraint_profile",
                "avoid_concurrency",
                "constraint_profile__free_block",
                "constraint_profile__resource_break",
                "constraint_profile__maximum_hour",
                "constraint_profile__maximum_workspan",
                "constraint_profile__travel_table",
                "tag__tag" #tags means the relation add in models, __tag means the relation table tag_id get the tag object
            )
            .order_by(self.list_default_order_column)
        )
        return_data=[]
        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"}
        }

        locations = self.listing_filter(request, locations)

        paginated_details = self.listing_pagination(request, locations)
        total = paginated_details["total"]
        paginated_data = paginated_details["paginated_data"]
        page = paginated_details["page"]

        for val in paginated_data:
            data={}
            data["id"] = val.id
            data["code"] = val.code
            data["name"] = val.name
            data['desc'] = val.desc
            data['department'] = val.department.name if val.department else None
            data['department_id'] = val.department_id
            data['zone'] = val.zone.name if val.zone else None
            data['zone_id'] = val.zone_id
            data['capacity'] = val.capacity
            data['area'] = val.area
            data['maximum_period'] = val.maximum_period
            data['contract_period'] = val.contract_period

            data["availability_id"] = val.availability.id if val.availability else None
            data["availability_name"] = val.availability.name if val.availability else "-"
            data["availability_pattern"] = val.availability.pattern if val.availability else val.availability_pattern
            data["start_preference_id"] = val.start_preference.id if val.start_preference else None
            data["start_preference_name"] = val.start_preference.name if val.start_preference else "-"
            data["start_preference_pattern"] = val.start_preference.pattern if val.start_preference else val.start_preference_pattern
            data["usage_preference_id"] = val.usage_preference.id if val.usage_preference else None
            data["usage_preference_name"] = val.usage_preference.name if val.usage_preference else "-"
            data["usage_preference_pattern"] = val.usage_preference.pattern if val.usage_preference else val.usage_preference_pattern

            data['suitability'] = [
                {"id": suit.id, "name": suit.name}
                for suit in val.suitability.all()
            ]
            data['shared_with_department'] = [
                {"id": dept.id, "name": dept.name}
                for dept in val.shared_with_department.all()
            ]
            data['avoid_concurrency'] = [
                {"id": avoid.id, "name": avoid.name}
                for avoid in val.avoid_concurrency.all()
            ]
            data['shared_with_all_department'] = val.shared_with_all_department
            data['constraint_profile'] = []
            for constraint_profile in val.constraint_profile.all():
                constraint_data = {
                    "id": constraint_profile.id,
                    "name": constraint_profile.name,
                    "code": constraint_profile.code,
                    "active_constraints": [],
                }

                for relation_key, relation_columns in relation_table.items():
                    relation_models = getattr(constraint_profile, relation_key, None)
                    if relation_models:
                        new_items = [
                            {
                                **{column: getattr(item, column) for column in relation_columns},
                                "category": relation_key,
                                "category_name": __("attr." + relation_key)
                            }
                            for item in relation_models.all()
                        ]
                        constraint_data["active_constraints"].extend(new_items)
                data["constraint_profile"].append(constraint_data)

            data["tag"] = [
                {"id": tag.tag.id, "name": tag.tag.name}
                for tag in val.tag.all()
            ]
            for i in range(1,11):
                extra_data_field = f"extra_data_{i}"
                data[extra_data_field] = getattr(val,extra_data_field,None)

            return_data.append(data)

        return {
            "total": total,
            "page": page,
            "data": return_data,
        }