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 AlimentationCommentairesSerializer
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_commentaires)
from ..utils_insertion import insert_Commentaires


class AlimentationCommentairesView(APIView):
    """ Vue pour alimenter la base avec les commentaires """

    permission_classes = [IsAuthenticated, IsAdminUser]
    serializer_class = AlimentationCommentairesSerializer

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


    def get(self, request):
        return Response("Formulaire d'alimentation d'OGURE NG pour les commentaires")


    @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)

            df_comments = read_files_by_type({
                FileTypes.COMMENTS: validator.validated_data.get('commentaires')
            }).get(DataFrameTypes.COMMENTS)

            if df_comments is not None:
                df = to_table_commentaires(df_comments)
                self.logger.info('Extraction des commentaires           ------> Succès')

                insert_Commentaires(df)
                self.logger.info('Insertion des commentaires            ------> Succès')
            else:
                self.logger.info('Mise à jour ignorée : commentaires')
            return Response({'Insertion réussie'})
        except (Http404, APIException):
            raise
        except BaseException:
            message = "Impossible d'alimenter le(s) référentiel(s)"
            self.logger.exception(message)
            raise APIException(message)
