# coding: utf-8

from django.db.models import Q

from procu.api import models
from procu.rest import generics
from procu.rest.permissions import StaffOnly
from . import serializers


class DashboardCreate(generics.CreateAPIView):
    permission_classes = (StaffOnly,)
    serializer_class = serializers.Create

    queryset = models.Dashboard.objects.filter(is_deleted=False)

    def perform_create(self, serializer):
        return serializer.save(author=self.request.user)


class DashboardRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (StaffOnly,)
    serializer_class = serializers.Retrieve

    def get_queryset(self):
        return models.Dashboard.objects.filter(
            Q(is_public=True) | Q(author=self.request.user), is_deleted=False
        ).prefetch_related('widgets')

    lookup_url_kwarg = 'dashboard_id'

    def get_serializer_class(self):
        if self.request.method == 'PATCH':
            return serializers.Update
        else:
            return serializers.Retrieve
