from collections import defaultdict

from django.contrib.postgres.aggregates import ArrayAgg
from django.db.models import Q
from rest_framework import serializers, status

from api.models import TtSuitability, TtTag, TtSetting, AuditTrail, AuditTrailDetails, TtDepartment, TtZone, \
    TtConstraintProfile, TtStaff, TtLocation, TtStudentSet
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator
from api.utils import decrypt_aes_128_cbc, encrypt_aes_128_cbc, log_critical_error, get_exception_detail, \
    bulk_sync_to_redis, get_ip, get_related_fk_table_ids
from rest_framework.exceptions import ValidationError
from api.translation import __
from backend.kafka import send_request
from backend.redis_client import redis_client


class ConstraintProfileDelete(AdminApiBase):
    def validate_request(self,request):
        rules = {
            "id": "required|array|exists:api.TtConstraintProfile,id",
        }
        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }
        # validate id first, cause need get constraint_profile 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.validate_request(request)

            action = "constraint_profile_delete"
            ids = request.data.get("id")

            constraint_profile = TtConstraintProfile.objects.filter(id__in=ids).prefetch_related("ttstudentset_set","ttlocation_set","ttstaff_set")
            constraint_profile_name = ",".join(constraint_profile.values_list("name", flat=True))
            ids = [c.id for c in constraint_profile.all()]
            staff_ids = set()
            location_ids = set()
            student_set_ids = set()
            for val in constraint_profile:
                staff_ids.update({relation.id for relation in val.ttstaff_set.all()})
                location_ids.update({relation.id for relation in val.ttlocation_set.all()})
                student_set_ids.update({relation.id for relation in val.ttstudentset_set.all()})

            TtConstraintProfile.objects.filter(id__in=ids).delete()

            # remove from redis
            redis_constraint_profile_table = "constraint_profile"
            redis_staff_table = "staff"
            redis_location_table = "location"
            redis_student_set_table = "student_set"
            redis_data = {
                "update": {},
                "delete": {}
            }
            # delete constraint_profile from redis
            for id in ids:
                redis_data["delete"].setdefault(redis_constraint_profile_table, []).append(id)

            # get latest data that have relation to deleted constraint_profile and update those constraint_profile column
            target_configs = [
                (redis_staff_table, TtStaff.objects.filter(id__in=staff_ids) if staff_ids else None),
                (redis_location_table, TtLocation.objects.filter(id__in=location_ids) if location_ids else None),
                (redis_student_set_table,TtStudentSet.objects.filter(id__in=student_set_ids) if student_set_ids else None),
            ]
            for table_name, queryset in target_configs:
                if queryset is not None:
                    items = queryset.prefetch_related("constraint_profile")

                    for item in items:
                        update_relation_data = {
                            "id": item.id,
                            "constraint_profile": [cp.id for cp in item.constraint_profile.all()],
                        }
                        redis_data["update"].setdefault(table_name, []).append(update_relation_data)
            bulk_sync_to_redis(redis_client,redis_data)

            audit_trail = AuditTrail.objects.create(
                user_id=request.user.id,
                type=self.audit_type,
                ip_address=get_ip(request)
            )
            remark_param = {
                "name": constraint_profile_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,
            )
            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)