from rest_framework import status

from api.models import EsInvigilator
from api.models.audit_trail import AuditTrail
from api.models.audit_trail_details import AuditTrailDetails
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator
from api.utils import log_critical_error, get_exception_detail, get_add_new_data, get_ip, get_next_available_code
from rest_framework.exceptions import ValidationError
from api.translation import __


class InvigilatorCreate(AdminApiBase):
    def validate_request(self,request):
        status_code_string = ",".join(str(v) for v in EsInvigilator.STATUS_TO_CODE.values())
        rules = {
            "code": "nullable|not_exists:api.EsInvigilator,code",
            "name": "required",
            "desc": "nullable",
            "email": "nullable",
            "phone": "nullable",
            "engagement_date": "nullable|date",
            "termination_date": "nullable|date",
            "department_id": "nullable|exists:api.EsDepartment,id",
            "tag": "nullable|array|exists:api.EsTag,id",
            "suitability": "nullable|array|exists:api.EsSuitability,id",
            "status": "required|in:"+status_code_string,
            "role": "nullable|array|exists:api.EsInvigilatorRole,id",
        }

        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }

        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)

        # custom error after basic validation

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

            old_new_data = {
                "old_data": None,
                "new_data": None,
            }

            action="invigilator_create" # this is for audit log only

            idata = {}
            # not insert to department table
            ignore_field = []
            valid_fields = {f.column for f in EsInvigilator._meta.fields}

            for key, val in request.data.items():
                if key not in ignore_field:
                    match key:
                        case _:
                            if key in valid_fields:#for insert, key can check in default part, cause if got special handle, i can check the way to use key also
                                # default the key will same as db column name
                                idata[key] = val

            code = request.data.get("code")
            if not code:
                idata["code"] = get_next_available_code(EsInvigilator, "code", "MV", 10)
            idata['created_by'] = request.user.id

            new_obj = EsInvigilator.objects.create(**idata)

            old_new_data['new_data']=get_add_new_data(new_obj)

            new_ids = request.data.get("tag", [])
            old_new_data = self.update_m2m_field(new_obj,'tag',None,new_ids,old_new_data,False,True)

            new_ids = request.data.get("suitability", [])
            old_new_data = self.update_m2m_field(new_obj,'suitability',None,new_ids,old_new_data)

            new_ids = request.data.get("role", [])
            old_new_data = self.update_m2m_field(new_obj,'role',None,new_ids,old_new_data)

            # insert audit trail and details
            # can insert the parent first, then only insert details
            audit_trail = AuditTrail.objects.create(
                user_id=request.user.id,
                type=self.audit_type,
                ip_address=get_ip(request)
            )

            # call to a function for insert details, so in future if want change to used worker, can modify in function only
            AuditTrailDetails.custom_insert(
                audit_trail=audit_trail,
                action=action,
                remark_param={
                    "code": new_obj.code,
                },
                new_data=old_new_data['new_data'],
            )

            response = {

            }

            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)