from collections import defaultdict

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

from api.models import TtDepartment, TtZone, TtTag, TtUsagePreference, TtAcademicTerm, TtWeek, TtSetting, TtPathway
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator
from api.utils import log_critical_error, get_exception_detail, get_related_fk_table_ids
from rest_framework.exceptions import ValidationError
from api.translation import __


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

            data = []
            related_data = get_related_fk_table_ids("TtAcademicTerm", ids,False,"name")
            for table_name,val in related_data.items():
                if table_name in TtAcademicTerm.DELETE_CONFIRMATION_TABLE:
                    details = list()
                    if table_name == "tt_pathway":
                        message = __("message.pathway_remove",count=len(set(val)))
                        pathway_details = TtPathway.get_pathway_details(val)
                        for pathway in pathway_details:
                            details.append({
                                "academic_term_name": pathway.academic_term.name,
                                "pos_name": pathway.pos.name,
                                "module_name": ", ".join(str(x) for x in pathway.module_name)
                            })
                    else:
                        message = ", ".join(str(x) for x in val)
                    data.append({
                        "delete_from": __("db_table_name."+table_name),
                        "message":message,
                        "details": details
                    })
            response = {
                "list": 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)