from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics
from rest_framework.filters import OrderingFilter

from partner import filters
from partner.models import Partner, PartnerToEstablishment
from partner.serializers import back as serializers
from utils.methods import get_permission_classes
from utils.permissions import IsEstablishmentManager, IsEstablishmentAdministrator


class PartnerLstView(generics.ListCreateAPIView):
    """Partner list/create view.
    Allows to get partners for current country, or create a new one.
    """
    queryset = Partner.objects.with_base_related()
    serializer_class = serializers.BackPartnerSerializer
    pagination_class = None
    filter_class = filters.PartnerFilterSet
    permission_classes = get_permission_classes(
        IsEstablishmentManager,
        IsEstablishmentAdministrator
    )


class EstablishmentPartners(generics.ListAPIView):
    queryset = PartnerToEstablishment.objects.with_base_related()
    serializer_class = serializers.PartnersForEstablishmentSerializer
    pagination_class = None
    filter_class = filters.PartnerToEstablishmentFilterSet
    filter_backends = (OrderingFilter, DjangoFilterBackend)
    ordering_fields = '__all__'
    ordering = '-partner_bind_date'
    permission_classes = get_permission_classes(
        IsEstablishmentManager,
        IsEstablishmentAdministrator
    )

    def get_queryset(self):
        return super().get_queryset().filter(establishment=self.kwargs['establishment_id'])


class PartnerRUDView(generics.RetrieveUpdateDestroyAPIView):
    """Partner RUD view."""
    queryset = Partner.objects.with_base_related()
    serializer_class = serializers.BackPartnerSerializer
    lookup_field = 'id'
    permission_classes = get_permission_classes(
        IsEstablishmentManager,
        IsEstablishmentAdministrator
    )


class PartnerPicturesListView(generics.RetrieveAPIView):
    lookup_field = 'id'
    serializer_class = serializers.PartnerPicturesSerializer
    queryset = Partner.objects.with_base_related()
    permission_classes = get_permission_classes(
        IsEstablishmentManager,
        IsEstablishmentAdministrator
    )


class BindPartnerToEstablishmentView(generics.CreateAPIView):
    serializer_class = serializers.PartnersForEstablishmentSerializer
    permission_classes = get_permission_classes(
        IsEstablishmentManager,
        IsEstablishmentAdministrator
    )


class UnbindPartnerFromEstablishmentView(generics.DestroyAPIView):
    serializer_class = serializers.PartnersForEstablishmentSerializer
    permission_classes = get_permission_classes(
        IsEstablishmentManager,
        IsEstablishmentAdministrator
    )

    def get_object(self):
        return get_object_or_404(PartnerToEstablishment, pk=self.kwargs['bind_id'])
