from django.forms import model_to_dict
from django.http import Http404
from rest_framework.exceptions import APIException
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView

from ..models import FMOB, Administre, FormationEmploi
from ..utils.decorators import class_logger
from .commun import (GestionnairePermission, execution_time_viewset,
                     query_count_viewset)


@class_logger
@execution_time_viewset
@query_count_viewset
class FicheDetailleeView(APIView):
    """
    Cette classe est dédiée au vue de la fiche détaillée des administrés
    """
    permission_classes = [IsAuthenticated, GestionnairePermission]

    def get(self, request: Request) -> Response:
        """La fonction get recupére les infos administrés

        :type request: rest_framework.request.Request
        :param request: Request contenant l'identifiant de l'administré

        :return:    - **Response** (*objet*): informations concernant l'administré, informations sur le formulaire de mobilité.
        """
        try:
            res = {"result": "error"}
            if 'administre_id' in request.query_params:
                administre_id = request.query_params['administre_id']
                annee_pam = request.query_params['pam__in']
                administre_id_pam = request.query_params['administre_id'] + annee_pam
                administre = Administre.objects.get(a_id_sap=administre_id)
                res = model_to_dict(administre, fields=[field.name for field in administre._meta.fields if field != 'a_liste_id_competences'])
                res['a_liste_id_competences'] = ','.join(list(administre.a_liste_id_competences.values_list('comp_libelle', flat=True)))
                fmobs = FMOB.objects.filter(administre_id=administre_id_pam)
                res["fmob"] = None
                res['pam'] = None

                if fmobs.exists():
                    fmob_dict = model_to_dict(fmobs[0])
                    res["fmob"] = fmob_dict

                res["fe"] = None
                fe = list(FormationEmploi.objects.filter(fe_code=administre.formation_emploi_id).values(
                    *('fe_code', 'fe_code_postal', 'fe_garnison_lieu', 'fe_libelle')))
                # if fe.exists():
                #     fe = fe[0]
                #     garnison_dict = model_to_dict()
                #     res["garnison"] = garnison_dict
                if len(fe):
                    res["fe"] = fe[0]
                res["conjoint"] = None
                conjoint = Administre.objects.filter(a_id_sap=administre.a_sap_conjoint)
                if conjoint.exists():
                    self.logger.debug('has conjoint')
                    conjoint_dict = model_to_dict(conjoint[0])
                    conjoint_dict['pam'] = None
                    conjoint_dict["fe"] = None
                    fe_conjoint = list(FormationEmploi.objects.filter(fe_code=conjoint_dict['formation_emploi']).values(
                        *('fe_code', 'fe_code_postal', 'fe_garnison_lieu', 'fe_libelle')))
                    if len(fe):
                        conjoint_dict["fe"] = fe_conjoint[0]

                        # Verifier si le conjoint est formobé
                    conjoint_dict["fmob_O_N"] = "Oui" if FMOB.objects.filter(administre_id=str(conjoint_dict['a_id_sap']) + annee_pam).exists() else "Non"
                    res["conjoint"] = conjoint_dict

                adm_affect = list(administre.adm_affec.values())
                adm_affect_sorted = sorted(adm_affect,  key=lambda d: d['affect_date'], reverse=True)
                for i in range(len(adm_affect_sorted)):
                    res['a_affectation{}'.format(i + 1)] = adm_affect_sorted[i]['affect_libelle']
                    res['a_date_affectation{}'.format(i + 1)] = adm_affect_sorted[i]['affect_date']

                adm_dip = list(administre.adm_dip.values())
                adm_dip_sorted = sorted(adm_dip,  key=lambda d: d['diplome_date'], reverse=True)
                for i in range(len(adm_dip)):
                    res['a_diplome_{}'.format(i + 1)] = adm_dip_sorted[i]['diplome_libelle']
                    res['a_diplome_{}_date'.format(i + 1)] = adm_dip_sorted[i]['diplome_date']
                    res['a_diplome_{}_note'.format(i + 1)] = adm_dip_sorted[i]['diplome_note']

                adm_fud = list(administre.adm_fud.values())
                adm_fud_sorted = sorted(adm_fud,  key=lambda d: d['fud_date_debut'], reverse=True)
                for i in range(len(adm_fud)):
                    res['a_fud_{}_dd'.format(i + 1)] = adm_fud_sorted[i]['fud_date_debut']
                    res['a_fud_{}_df'.format(i + 1)] = adm_fud_sorted[i]['fud_date_fin']
                    res['a_fud_{}_l'.format(i + 1)] = adm_fud_sorted[i]['fud_libelle']

                adm_not = list(administre.adm_not.values())
                adm_not_sorted = sorted(adm_not,  key=lambda d: d['no_age_annees'], reverse=False)
                for i in range(len(adm_not_sorted)):
                    res['no_annne_de_notation_A_{}'.format(i + 1)] = adm_not_sorted[i]['no_annne_de_notation']
                    res['no_nr_ou_iris_A_{}'.format(i + 1)] = adm_not_sorted[i]['no_nr_ou_iris']
                    res['no_rac_ou_iris_cumule_A_{}'.format(i + 1)] = adm_not_sorted[i]['no_rac_ou_iris_cumule']
                    res['no_rf_qsr_A_{}'.format(i + 1)] = adm_not_sorted[i]['no_rf_qsr']
                    res['no_aptitude_emploie_sup_A_{}'.format(i + 1)] = adm_not_sorted[i]['no_aptitude_emploie_sup']
                    res['no_potentiel_responsabilite_sup_A_{}'.format(i + 1)] = adm_not_sorted[i]['no_potentiel_responsabilite_sup']
                    res['no_age_annees_A_{}'.format(i + 1)] = adm_not_sorted[i]['no_age_annees']
            return Response(res)
        except (Http404, APIException):
            raise
        except:
            message = "impossible d'afficher la vue détaillée"
            self.logger.exception(message)
            raise APIException(message)
