from rest_framework import serializers, status
from api.models import TtUsagePreference, TtTimeBlock, TtSetting
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 decrypt_aes_128_cbc, encrypt_aes_128_cbc, generate_kafka_data, log_critical_error, \
    get_exception_detail, \
    get_add_new_data, get_ip, bulk_sync_to_redis, get_next_available_code, get_start_and_end_slot
from rest_framework.exceptions import ValidationError
from api.translation import __
from backend.kafka import send_request
from backend.redis_client import redis_client


class TimeBlockCreate(AdminApiBase):
    def validate_request(self,request,slot_per_week):
        # FE will request by pattern, so can reduce the changes from FE, and BE will convert this pattern become start_slot and end_slot
        rules = {
            "code": "nullable|not_exists:api.TtTimeBlock,code",
            "name": "required",
            "desc": "nullable",
            "department_id": "nullable|exists:api.TtDepartment,id",
            "pattern": "required|char_count:" + slot_per_week + "|regex:[01]+",
            "tag": "nullable|array|exists:api.TtTag,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:
            setting_params = {
                "slot_per_week",
            }
            settings = TtSetting.get_multiple_setting(setting_params)
            slot_per_week = settings["slot_per_week"]
            self.validate_request(request,slot_per_week)
            old_new_data = {
                "old_data": None,
                "new_data": None,
            }

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

            idata = {}
            ignore_field = []
            valid_fields = {f.column for f in TtTimeBlock._meta.fields}

            for key, val in request.data.items():
                if key not in ignore_field:
                    match key:
                        case "pattern":
                            start_slot, end_slot = get_start_and_end_slot(val)
                            idata["start_slot"] = start_slot
                            idata["end_slot"] = end_slot
                        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
            # if FE no pass in code or is null or empty, will used default code
            code = request.data.get("code")
            if not code:
                idata["code"] = get_next_available_code(TtTimeBlock, "code", "MV", 10)


            idata['status'] = TtTimeBlock.STATUS_TO_CODE['active']
            idata['created_by'] = request.user.id

            time_block = TtTimeBlock.objects.create(**idata)

            old_new_data['new_data']=get_add_new_data(time_block)

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

            redis_time_block_table = "time_block"
            # from here make it same name as db first, got different, only do extra handle
            redis_time_block_column = [
                "id", "code", "name", "start_slot","end_slot", "department_id"
            ]
            redis_data = {
                "insert": {},
            }
            redis_time_block_data = {}
            for column in redis_time_block_column:
                match column:
                    case _:
                        redis_time_block_data[column] = getattr(time_block, column)
            redis_data["insert"].setdefault(redis_time_block_table, []).append(redis_time_block_data)

            bulk_sync_to_redis(redis_client, redis_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)
            )
            remark_param = {
                "name":time_block.name,
            }

            # 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=remark_param,
                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)