import pandas as pd
from django.db.transaction import atomic
from django.http import Http404
from rest_framework.exceptions import APIException
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from ..serializers import SuppressionAdministresSerializer
from ..utils.alimentation_decorators import (data_perf_logger_factory,
                                             get_data_logger)
from ..utils.decorators import execution_time, query_count
from ..utils_extraction import (DataFrameTypes, FileTypes, read_files_by_type,
                                to_table_suppression_administres)
from ..utils_insertion import suppression_administres


class SuppressionAdministresView(APIView):
    """ Vue pour supprimer les administrés de la base """

    permission_classes = [IsAuthenticated, IsAdminUser]
    serializer_class = SuppressionAdministresSerializer

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.logger = get_data_logger(self)


    def get(self, request):
        return Response("Formulaire d\'OGURE NG permettant de supprimer des administés de la base de données")


    @atomic
    @execution_time(logger_factory=data_perf_logger_factory)
    @query_count(logger_factory=data_perf_logger_factory)
    def post(self, request):
        """
        Charge le(s) fichier(s) et met à jour la base.

        :param request: requête, contient les fichiers
        :type  request: class:`rest_framework.request.Request`

        :raises: class:`rest_framework.exceptions.APIException`

        :return: réponse
        :rtype:  class:`rest_framework.response.Response`
        """
        try:
            validator = self.serializer_class(data=request.data)
            validator.is_valid(raise_exception=True)
            adm_suppr = 0

            df_adm_suppr = read_files_by_type({
                FileTypes.ADM_SUPPR: validator.validated_data.get('administres')
            }).get(DataFrameTypes.ADM_SUPPR)

            if df_adm_suppr is not None:
                df = to_table_suppression_administres(df_adm_suppr)
                self.logger.info('Extraction des administés à supprimer ------> Succès')
                adm_suppr = suppression_administres(df)
                self.logger.info('Suppression des administrés           ------> Succès')
            else:
                self.logger.info('Mise à jour ignorée : suppression des administrés')
            return Response({f'Suppression de {adm_suppr} administré(s) réussie'})
        except (Http404, APIException):
            raise
        except BaseException:
            message = "Echec de la suppression"
            self.logger.exception(message)
            raise APIException(message)
