"""Notification app common views."""
from django.shortcuts import get_object_or_404
from rest_framework import generics, permissions
from rest_framework.response import Response
from notification import models
from notification.serializers import common as serializers


class SubscribeView(generics.GenericAPIView):
    """Subscribe View."""

    queryset = models.Subscriber.objects.all()
    permission_classes = (permissions.AllowAny, )
    serializer_class = serializers.SubscribeSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(data=serializer.data)


class SubscribeInfoView(generics.RetrieveAPIView):
    """Subscribe info view."""

    lookup_field = 'update_code'
    lookup_url_kwarg = 'code'
    permission_classes = (permissions.AllowAny, )
    queryset = models.Subscriber.objects.all()
    serializer_class = serializers.SubscribeSerializer


class SubscribeInfoAuthUserView(generics.ListAPIView):
    """Subscribe info auth user view."""

    permission_classes = (permissions.IsAuthenticated, )
    serializer_class = serializers.SubscribeSerializer

    def get_queryset(self):
        user = self.request.user
        queryset = self.filter_queryset(models.Subscriber.objects.all())
        return queryset.filter(user=user)


class UnsubscribeView(generics.GenericAPIView):
    """Unsubscribe view."""

    lookup_field = 'update_code'
    lookup_url_kwarg = 'code'
    permission_classes = (permissions.AllowAny, )
    queryset = models.Subscriber.objects.all()
    serializer_class = serializers.SubscribeSerializer

    def patch(self, request, *args, **kw):
        obj = self.get_object()
        obj.unsubscribe()
        serializer = self.get_serializer(instance=obj)
        return Response(data=serializer.data)


class UnsubscribeAuthUserView(generics.GenericAPIView):
    """Unsubscribe auth user view."""

    permission_classes = (permissions.IsAuthenticated, )
    queryset = models.Subscriber.objects.all()
    serializer_class = serializers.SubscribeSerializer

    def patch(self, request, *args, **kw):
        user = request.user
        obj = get_object_or_404(models.Subscriber, user=user)
        obj.unsubscribe()
        serializer = self.get_serializer(instance=obj)
        return Response(data=serializer.data)


class SubscriptionTypesView(generics.ListAPIView):
    pagination_class = None
    permission_classes = (permissions.AllowAny,)
    queryset = models.SubscriptionType.objects.all()
    serializer_class = serializers.SubscriptionTypeSerializer

