from django.shortcuts import get_object_or_404
from rest_framework import generics, permissions, pagination

from collection import models
from collection.serializers import common as serializers
from establishment.serializers import EstablishmentSimilarSerializer
from utils.pagination import ProjectPageNumberPagination, ProjectMobilePagination


# Mixins
class CollectionViewMixin(generics.GenericAPIView):
    """Mixin for Collection view"""
    model = models.Collection
    permission_classes = (permissions.AllowAny,)
    serializer_class = serializers.CollectionSerializer

    def get_queryset(self):
        """Override get_queryset method."""
        return models.Collection.objects.published() \
                                        .by_country_code(code=self.request.country_code) \
                                        .order_by('-on_top', '-created')


class GuideViewMixin(generics.GenericAPIView):
    """Mixin for Guide view"""
    model = models.Guide
    queryset = models.Guide.objects.all()


# Views
# Collections
class CollectionListView(CollectionViewMixin, generics.ListAPIView):
    """List Collection view."""


class CollectionHomePageView(CollectionListView):
    """Collection list view for home page."""

    def get_queryset(self):
        """Override get_queryset."""
        return super(CollectionHomePageView, self).get_queryset() \
                                                  .filter_all_related_gt(3)


class CollectionDetailView(CollectionViewMixin, generics.RetrieveAPIView):
    """Retrieve detail of Collection instance."""
    lookup_field = 'slug'
    serializer_class = serializers.CollectionBaseSerializer


class CollectionEstablishmentListView(CollectionListView):
    """Retrieve list of establishment for collection."""
    lookup_field = 'slug'
    pagination_class = ProjectMobilePagination
    serializer_class = EstablishmentSimilarSerializer

    def get_queryset(self):
        """
        Override get_queryset method.
        """
        queryset = super(CollectionEstablishmentListView, self).get_queryset()
        # Perform the lookup filtering.
        collection = get_object_or_404(queryset, slug=self.kwargs['slug'])

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

        return collection.establishments.published().annotate_in_favorites(self.request.user)


# Guide
class GuideListView(GuideViewMixin, generics.ListAPIView):
    """List Guide view"""
    permission_classes = (permissions.AllowAny,)
    serializer_class = serializers.GuideBaseSerializer


class GuideRetrieveView(GuideViewMixin, generics.RetrieveAPIView):
    """Retrieve Guide view"""
    permission_classes = (permissions.AllowAny,)
    serializer_class = serializers.GuideBaseSerializer
