from rest_framework import status

from api.models import EsStaff, EsDepartment, EsTag
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator
from api.utils import log_critical_error, get_exception_detail
from rest_framework.exceptions import ValidationError
from api.translation import __


class StaffRules(AdminApiBase):
    def validate_request(self,request):
        rules = {
            "id": "nullable|array|exists:api.EsStaff,id",
        }
        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }
        # validate id first, cause need get staff 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 = []
            staff = None
            if isinstance(ids, (list, tuple)) and len(ids) == 1:
                staff = (
                    EsStaff.objects
                    .select_related("department")
                    .prefetch_related(
                        "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 staff:
                info = {
                    "code": staff.code,
                    "name": staff.name,
                    "desc": staff.desc,
                    "department_id": staff.department_id,
                    "email": staff.email,
                    "phone": staff.phone,
                    "tag": staff.tag.all().values_list("tag_id",flat=True),
                    "status": staff.phone,
                    "status_text": __("attr.staff_status." + str(staff.status)),
                }
                for i in range(1, 11):
                    extra_data_field = f"extra_data_{i}"
                    info[extra_data_field] = getattr(staff, extra_data_field, None)

            models = {
                "department": (EsDepartment, ["id", "code", "name"]),
                "tag": (EsTag, ["id", "code", "name"]),
            }

            data = {}
            data['delete_confirmation_api'] = False
            data["allow_remove"] = [
                "desc",
                "department_id",
                "email",
                "phone",
                "tag",
                *[f"extra_data_{i}" for i in range(1, 11)]
            ]

            data['status'] = [
                {
                    "id": val,
                    "name": __(f"attr.user_status.{val}")
                }
                for key, val in EsStaff.STATUS_TO_CODE.items()
            ]

            for key, (model, fields) in models.items():
                data[key] = list(
                    model.objects.filter(status=model.STATUS_TO_CODE['active']).values(*fields)
                )

            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)