"""Back office views for app advertisement"""
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework import permissions
from django.shortcuts import get_object_or_404

from main.serializers import PageExtendedSerializer
from advertisement.models import Advertisement
from advertisement.serializers import (AdvertisementBaseSerializer,
                                       AdvertisementDetailSerializer)


class AdvertisementBackOfficeViewMixin(generics.GenericAPIView):
    """Base back office advertisement view."""

    pagination_class = None
    permission_classes = (permissions.IsAuthenticated, )

    def get_queryset(self):
        """Overridden get queryset method."""
        return Advertisement.objects.with_base_related()


class AdvertisementListCreateView(AdvertisementBackOfficeViewMixin, generics.ListCreateAPIView):
    """List|Create advertisement view."""

    serializer_class = AdvertisementBaseSerializer


class AdvertisementRUDView(AdvertisementBackOfficeViewMixin,
                           generics.RetrieveUpdateDestroyAPIView):
    """Retrieve|Update|Destroy advertisement page view."""

    serializer_class = AdvertisementDetailSerializer


class AdvertisementPageCreateView(AdvertisementBackOfficeViewMixin,
                                  generics.CreateAPIView):
    """Create advertisement page view."""

    serializer_class = PageExtendedSerializer

    def get_object(self):
        """Returns the object the view is displaying."""
        ad_qs = Advertisement.objects.all()
        filtered_ad_qs = self.filter_queryset(ad_qs)

        ad = get_object_or_404(filtered_ad_qs, pk=self.kwargs.get('pk'))

        # May raise a permission denied
        self.check_object_permissions(self.request, ad)

        return ad

    def get_queryset(self):
        """Overridden get_queryset method."""
        return self.get_object().pages.all()

    def create(self, request, *args, **kwargs):
        """Overridden create method."""
        request.data.update({'advertisement': self.get_object().pk})
        super().create(request, *args, **kwargs)
        return Response(status=status.HTTP_200_OK)


class AdvertisementPageUDView(AdvertisementBackOfficeViewMixin,
                              generics.UpdateAPIView,
                              generics.DestroyAPIView):
    """Update|Destroy advertisement page view."""

    serializer_class = PageExtendedSerializer

    def get_object(self):
        """Returns the object the view is displaying."""
        ad_qs = Advertisement.objects.all()
        filtered_ad_qs = self.filter_queryset(ad_qs)

        ad = get_object_or_404(filtered_ad_qs, pk=self.kwargs.get('ad_pk'))
        page = get_object_or_404(ad.pages.all(), pk=self.kwargs.get('page_pk'))

        # May raise a permission denied
        self.check_object_permissions(self.request, page)

        return page
