"""Location app views."""
from rest_framework import generics

from location import models, serializers
from location.views import common
from utils.permissions import IsCountryAdmin
from utils.views import CreateDestroyGalleryViewMixin
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from django.shortcuts import get_object_or_404
from django.db import IntegrityError
from utils.serializers import ImageBaseSerializer
from location.filters import RegionFilter

from location import filters


# Address


class AddressListCreateView(common.AddressViewMixin, generics.ListCreateAPIView):
    """Create view for model Address."""
    serializer_class = serializers.AddressDetailSerializer
    queryset = models.Address.objects.all()
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]


class AddressRUDView(common.AddressViewMixin, generics.RetrieveUpdateDestroyAPIView):
    """RUD view for model Address."""
    serializer_class = serializers.AddressDetailSerializer
    queryset = models.Address.objects.all()
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]


# City
class CityListCreateView(common.CityViewMixin, generics.ListCreateAPIView):
    """Create view for model City."""
    serializer_class = serializers.CitySerializer
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]
    # queryset = models.City.objects.all()
    filter_class = filters.CityBackFilter

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


class CityListSearchView(common.CityViewMixin, generics.ListCreateAPIView):
    """Create view for model City."""
    serializer_class = serializers.CitySerializer
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]
    queryset = models.City.objects.all()
    filter_class = filters.CityBackFilter
    pagination_class = None


class CityRUDView(common.CityViewMixin, generics.RetrieveUpdateDestroyAPIView):
    """RUD view for model City."""
    serializer_class = serializers.CitySerializer
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]


class CityGalleryCreateDestroyView(common.CityViewMixin,
                                   CreateDestroyGalleryViewMixin):
    """Resource for a create gallery for product for back-office users."""
    serializer_class = serializers.CityGallerySerializer
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]

    def get_object(self):
        """
        Returns the object the view is displaying.
        """
        city_qs = self.filter_queryset(self.get_queryset())

        city = get_object_or_404(city_qs, pk=self.kwargs.get('pk'))
        gallery = get_object_or_404(city.city_gallery, image_id=self.kwargs.get('image_id'))

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

        return gallery

    def create(self, request, *args, **kwargs):
        try:
            return super(CityGalleryCreateDestroyView, self).create(request, *args, **kwargs)
        except IntegrityError as e:
            if not 'unique constraint' in e.args[0]:
                raise e
            models.CityGallery.objects.filter(city=kwargs['pk'], is_main=request.data['is_main']).delete()
            return super(CityGalleryCreateDestroyView, self).create(request, *args, **kwargs)


class CityGalleryListView(common.CityViewMixin,
                          generics.ListAPIView):
    """Resource for returning gallery for product for back-office users."""
    serializer_class = ImageBaseSerializer
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]

    def get_object(self):
        """Override get_object method."""
        qs = super(CityGalleryListView, self).get_queryset()
        city = get_object_or_404(qs, pk=self.kwargs['pk'])

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

        return city

    def get_queryset(self):
        """Override get_queryset method."""
        return self.get_object().crop_gallery


# Region
class RegionListCreateView(common.RegionViewMixin, generics.ListCreateAPIView):
    """Create view for model Region"""
    pagination_class = None
    serializer_class = serializers.RegionSerializer
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]
    ordering_fields = '__all__'
    filter_class = RegionFilter


class RegionRUDView(common.RegionViewMixin, generics.RetrieveUpdateDestroyAPIView):
    """Retrieve view for model Region"""
    serializer_class = serializers.RegionSerializer
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]


# Country
class CountryListCreateView(generics.ListCreateAPIView):
    """List/Create view for model Country."""
    queryset = models.Country.objects.all()
    serializer_class = serializers.CountryBackSerializer
    pagination_class = None
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]


class CountryRUDView(generics.RetrieveUpdateDestroyAPIView):
    """RUD view for model Country."""
    serializer_class = serializers.CountryBackSerializer
    permission_classes = [IsAuthenticatedOrReadOnly | IsCountryAdmin]
    queryset = models.Country.objects.all()
