from django.contrib.contenttypes.models import ContentType
from django.utils.translation import gettext_lazy as _
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics, status
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response

from establishment.models import Employee
from establishment.serializers.back import EmployeeBackSerializers
from main import serializers
from main import tasks
from main.filters import AwardFilter
from main.models import Award, Footer, PageType, Panel, SiteFeature, Feature, AwardType
from main.serializers.back import PanelSerializer
from main.views import SiteSettingsView, SiteListView
from utils.methods import get_permission_classes


class AwardLstView(generics.ListCreateAPIView):
    """Award list create view."""
    queryset = Award.objects.all().with_base_related()
    serializer_class = serializers.BackAwardSerializer
    permission_classes = get_permission_classes()
    filterset_class = AwardFilter


class AwardCreateAndBind(generics.CreateAPIView):
    """Award create and bind to employee by id"""
    queryset = Award.objects.all().with_base_related()
    serializer_class = serializers.BackAwardEmployeeCreateSerializer
    permission_classes = get_permission_classes()

    def create(self, request, *args, **kwargs):
        """Overridden create method."""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        response_serializer = EmployeeBackSerializers(Employee.objects.get(pk=kwargs['employee_id']))
        headers = self.get_success_headers(response_serializer.data)
        return Response(response_serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class AwardRUDView(generics.RetrieveUpdateDestroyAPIView):
    """Award RUD view."""
    queryset = Award.objects.all().with_base_related()
    serializer_class = serializers.BackAwardSerializer
    permission_classes = get_permission_classes()
    lookup_field = 'id'


class AwardTypesListView(generics.ListAPIView):
    """AwardType List view."""
    pagination_class = None
    serializer_class = serializers.AwardTypeBaseSerializer
    permission_classes = get_permission_classes()
    filter_backends = (DjangoFilterBackend,)
    ordering_fields = '__all__'
    lookup_field = 'id'
    filterset_fields = (
        'id',
        'name',
    )

    def get_queryset(self):
        """Overridden get_queryset method."""
        if hasattr(self, 'request') and hasattr(self.request, 'country_code'):
            return AwardType.objects.by_country_code(self.request.country_code)
        return AwardType.objects.none()


class ContentTypeView(generics.ListAPIView):
    """ContentType list view"""
    queryset = ContentType.objects.all()
    serializer_class = serializers.ContentTypeBackSerializer
    permission_classes = get_permission_classes()
    filter_backends = (DjangoFilterBackend,)
    ordering_fields = '__all__'
    lookup_field = 'id'
    filterset_fields = (
        'id',
        'model',
        'app_label',
    )


class FeatureBackView(generics.ListCreateAPIView):
    """Feature list or create View."""
    serializer_class = serializers.FeatureSerializer
    queryset = Feature.objects.all()
    permission_classes = get_permission_classes()


class SiteFeatureBackView(generics.ListCreateAPIView):
    """Feature list or create View."""
    serializer_class = serializers.SiteFeatureSerializer
    queryset = SiteFeature.objects.all()
    pagination_class = None
    permission_classes = get_permission_classes()


class FeatureRUDBackView(generics.RetrieveUpdateDestroyAPIView):
    """Feature RUD View."""
    serializer_class = serializers.FeatureSerializer
    queryset = SiteFeature.objects.all()
    permission_classes = get_permission_classes()


class SiteFeatureRUDBackView(generics.RetrieveUpdateDestroyAPIView):
    """Feature RUD View."""
    serializer_class = serializers.SiteFeatureSerializer
    queryset = SiteFeature.objects.all()
    permission_classes = get_permission_classes()


class SiteSettingsBackOfficeView(SiteSettingsView):
    """Site settings View."""
    serializer_class = serializers.SiteSerializer
    permission_classes = get_permission_classes()


class SiteListBackOfficeView(SiteListView):
    """Site settings View."""
    serializer_class = serializers.SiteSerializer
    permission_classes = get_permission_classes()


class FooterBackView(generics.ListCreateAPIView):
    """Footer back list/create view."""
    serializer_class = serializers.FooterBackSerializer
    queryset = Footer.objects.all()
    permission_classes = get_permission_classes()


class FooterRUDBackView(generics.RetrieveUpdateDestroyAPIView):
    """Footer back RUD view."""
    serializer_class = serializers.FooterBackSerializer
    queryset = Footer.objects.all()
    permission_classes = get_permission_classes()


class PageTypeListCreateView(generics.ListCreateAPIView):
    """PageType back office view."""
    pagination_class = None
    serializer_class = serializers.PageTypeBaseSerializer
    queryset = PageType.objects.all()
    permission_classes = get_permission_classes()


class PanelsListCreateView(generics.ListCreateAPIView):
    """Custom panels view."""
    serializer_class = PanelSerializer
    queryset = Panel.objects.all()
    permission_classes = get_permission_classes()


class PanelsRUDView(generics.RetrieveUpdateDestroyAPIView):
    """Custom panels view."""
    serializer_class = PanelSerializer
    queryset = Panel.objects.all()
    permission_classes = get_permission_classes()


class PanelsExecuteView(generics.ListAPIView):
    """Custom panels view."""
    queryset = Panel.objects.all()
    permission_classes = get_permission_classes()

    def list(self, request, *args, **kwargs):
        panel = get_object_or_404(Panel, id=self.kwargs['pk'])
        return Response(panel.execute_query(request))


class PanelsExportCSVView(PanelsExecuteView):
    """Export panels via csv view."""
    queryset = Panel.objects.all()
    permission_classes = get_permission_classes()

    def list(self, request, *args, **kwargs):
        panel = get_object_or_404(Panel, id=self.kwargs['pk'])
        # make task for celery
        tasks.send_export_to_email.delay(
            panel_id=panel.id, user_id=request.user.id)
        return Response(
            {"success": _('The file will be sent to your email.')},
            status=status.HTTP_200_OK
        )


class PanelsExecuteXLSView(PanelsExecuteView):
    """Export panels via xlsx view."""
    queryset = Panel.objects.all()
    permission_classes = get_permission_classes()

    def list(self, request, *args, **kwargs):
        panel = get_object_or_404(Panel, id=self.kwargs['pk'])
        # make task for celery
        tasks.send_export_to_email.delay(
            panel_id=panel.id, user_id=request.user.id, file_type='xls')
        return Response(
            {"success": _('The file will be sent to your email.')},
            status=status.HTTP_200_OK
        )
