from django.shortcuts import get_object_or_404
from django.utils.translation import gettext_lazy as _
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics
from rest_framework import mixins, permissions, viewsets
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response

from collection import models, serializers
from collection import tasks
from utils.views import BindObjectMixin


class CollectionViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """ViewSet for Collection model."""

    # pagination_class = None
    permission_classes = (permissions.AllowAny,)
    serializer_class = serializers.CollectionBackOfficeSerializer

    def get_queryset(self):
        """Overridden method 'get_queryset'."""
        qs = models.Collection.objects.all().order_by('-created')
        if self.request.country_code:
            qs = qs.by_country_code(self.request.country_code)
        return qs


class GuideBaseView(generics.GenericAPIView):
    """ViewSet for Guide model."""
    serializer_class = serializers.GuideBaseSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def get_queryset(self):
        """Overridden get_queryset method."""
        return models.Guide.objects.with_base_related() \
                                   .annotate_restaurant_counter() \
                                   .annotate_shop_counter() \
                                   .annotate_wine_counter() \
                                   .annotate_present_objects_counter() \
                                   .distinct()


class GuideFilterBaseView(generics.GenericAPIView):
    """ViewSet for GuideFilter model."""
    pagination_class = None
    queryset = models.GuideFilter.objects.all()
    serializer_class = serializers.GuideFilterBaseSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)


class GuideElementBaseView(generics.GenericAPIView):
    """Base view for GuideElement model."""
    pagination_class = None
    queryset = models.GuideElement.objects.all()
    serializer_class = serializers.GuideElementBaseSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)


class AdvertorialBaseView(generics.GenericAPIView):
    """Base view for Advertorial model."""
    pagination_class = None
    queryset = models.Advertorial.objects.all()
    serializer_class = serializers.AdvertorialBaseSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)


class CollectionBackOfficeViewSet(mixins.CreateModelMixin,
                                  mixins.UpdateModelMixin,
                                  mixins.DestroyModelMixin,
                                  mixins.RetrieveModelMixin,
                                  BindObjectMixin,
                                  CollectionViewSet):
    """ViewSet for Collection model for BackOffice users."""

    permission_classes = (permissions.IsAuthenticated,)
    queryset = models.Collection.objects.all()
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    serializer_class = serializers.CollectionBackOfficeSerializer
    bind_object_serializer_class = serializers.CollectionBindObjectSerializer

    ordering_fields = ('rank', 'start')
    ordering = ('-start', )

    def perform_binding(self, serializer):
        data = serializer.validated_data
        collection = data.pop('collection')
        obj_type = data.get('type')
        related_object = data.get('related_object')
        if obj_type == self.bind_object_serializer_class.ESTABLISHMENT:
            collection.establishments.add(related_object)
        elif obj_type == self.bind_object_serializer_class.PRODUCT:
            collection.products.add(related_object)

    def perform_unbinding(self, serializer):
        data = serializer.validated_data
        collection = data.pop('collection')
        obj_type = data.get('type')
        related_object = data.get('related_object')
        if obj_type == self.bind_object_serializer_class.ESTABLISHMENT:
            collection.establishments.remove(related_object)
        elif obj_type == self.bind_object_serializer_class.PRODUCT:
            collection.products.remove(related_object)


class GuideListCreateView(GuideBaseView,
                          generics.ListCreateAPIView):
    """View for Guide model for BackOffice users."""


class GuideFilterCreateView(GuideFilterBaseView,
                            generics.CreateAPIView):
    """View for GuideFilter model for BackOffice users."""
    def post(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)
        return Response(status=status.HTTP_200_OK)


class GuideElementListView(GuideElementBaseView,
                           generics.ListAPIView):
    """View for model GuideElement for back office users."""

    def get_queryset(self):
        """Overridden get_queryset method."""
        guide = get_object_or_404(models.Guide.objects.all(), pk=self.kwargs.get('pk'))
        node = models.GuideElement.objects.get_root_node(guide)
        if node:
            return node.get_children()
        else:
            return models.GuideElement.objects.none()


class GuideUpdateView(GuideBaseView):
    """View for model GuideElement for back office users."""

    def get(self, request, *args, **kwargs):
        """POST-method to regenerate elements of guide instance."""
        guide = get_object_or_404(models.Guide.objects.all(),
                                  pk=self.kwargs.get('pk'))
        guide.regenerate_elements()
        return Response(status=status.HTTP_200_OK)


class AdvertorialCreateView(AdvertorialBaseView,
                            generics.CreateAPIView):
    """View for model Advertorial for back office users."""

    def post(self, request, *args, **kwargs):
        """Overridden post method."""
        super(AdvertorialCreateView, self).create(request, *args, **kwargs)
        return Response(status=status.HTTP_200_OK)


class AdvertorialDestroyView(AdvertorialBaseView,
                             generics.DestroyAPIView):
    """View for model Advertorial for back office users."""
    lookup_url_kwarg = 'advertorial_pk'

    def delete(self, request, *args, **kwargs):
        """Overridden delete method."""
        return self.destroy(request, *args, **kwargs)


class GuideElementExportCSVView(generics.ListAPIView):
    """Guide element export csv view."""
    pagination_class = None
    queryset = models.GuideElement.objects.all()
    serializer_class = serializers.GuideElementBaseSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def get(self, request, *args, **kwargs):
        """Overridden get_queryset method."""
        guide = get_object_or_404(
            models.Guide.objects.all(), pk=self.kwargs.get('pk'))
        tasks.export_guide(guide_id=guide.id, user_id=request.user.id)
        return Response({"success": _('The file will be sent to your email.')},
                        status=status.HTTP_200_OK)


class GuideElementExportXMLView(generics.ListAPIView):
    """Guide element export xml view."""
    pagination_class = None
    queryset = models.GuideElement.objects.all()
    serializer_class = serializers.GuideElementBaseSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def get(self, request, *args, **kwargs):
        """Overridden get_queryset method."""
        guide = get_object_or_404(
            models.Guide.objects.all(), pk=self.kwargs.get('pk'))
        tasks.export_guide(guide_id=guide.id, user_id=request.user.id, file_type='xml')
        return Response({"success": _('The file will be sent to your email.')},
                        status=status.HTTP_200_OK)


class GuideElementExportDOCView(generics.ListAPIView):
    """Guide element export doc view."""
    pagination_class = None
    queryset = models.GuideElement.objects.all()
    serializer_class = serializers.GuideElementBaseSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def get(self, request, *args, **kwargs):
        """Overridden get_queryset method."""
        guide = get_object_or_404(
            models.Guide.objects.all(), pk=self.kwargs.get('pk'))
        # todo: put in GuideElement model
        tasks.export_guide(guide_id=guide.id, user_id=request.user.id, file_type='doc')
        return Response({"success": _('The file will be sent to your email.')},
                        status=status.HTTP_200_OK)
