from rest_framework import generics

from comment import models
from comment.serializers import CommentBaseSerializer
from utils.methods import get_permission_classes
from utils.permissions import IsModerator


class CommentLstView(generics.ListCreateAPIView):
    """Comment list create view."""
    def get_queryset(self):
        from product.models import Product
        from establishment.models import Establishment

        allowed = {
            "product": Product.__name__.lower(),
            "establishment": Establishment.__name__.lower()
        }

        qs = models.Comment.objects.with_base_related()

        if "object" not in self.kwargs and "type" not in self.kwargs:
            qs = qs.filter(status=models.Comment.WAITING)

        if "object" in self.kwargs:
            qs = qs.by_object_id(self.kwargs["object"])

        if "type" in self.kwargs and self.kwargs["type"] in allowed:
            model = allowed[self.kwargs["type"]]
            qs = qs.by_content_type(self.kwargs["type"], model)

        return qs.order_by('-created')

    serializer_class = CommentBaseSerializer
    queryset = models.Comment.objects.all()
    permission_classes = get_permission_classes(IsModerator)


class CommentRUDView(generics.RetrieveUpdateDestroyAPIView):
    """Comment RUD view."""
    serializer_class = CommentBaseSerializer
    queryset = models.Comment.objects.all()
    permission_classes = get_permission_classes(IsModerator)
    lookup_field = 'id'
