from collections import defaultdict
from rest_framework import serializers, status

from api.models import TtDepartment, TtZone, TtTag, TtUsagePreference, TtAcademicTerm, TtWeek, TtSetting, TtModule, \
    TtPathway, TtModuleGroup
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 ModuleGroupDeleteConfirmation(AdminApiBase):
    def validate_request(self,request):
        rules = {
            "id": "nullable|array|exists:api.TtModuleGroup,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("TtModuleGroup", ids,False,"name")
            # for table_name,val in related_data.items():
            #     # if table_name in TtModuleGroup.DELETE_CONFIRMATION_TABLE:
            #     message = ", ".join(str(x) for x in val)
            #     data.append({
            #         "delete_from": __("db_table_name."+table_name),
            #         "message":message
            #     })

            pathway = TtPathway.objects.filter(
                pos_module_group_module__pos_module_group__module_group_id__in=ids,
            ).distinct()
            if pathway:
                pathway_details = TtPathway.get_pathway_details(pathway.values_list("id",flat=True))
                details = list()
                for val in pathway_details:
                    details.append({
                        "academic_term_name": val.academic_term.name,
                        "pos_name": val.pos.name,
                        "module_name": ", ".join(str(x) for x in val.module_name)
                    })
                data.append({
                    "delete_from": __("db_table_name.tt_pathway"),
                    "message": __("message.pathway_remove", count=len(pathway)),
                    "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)