# -*- encoding: utf-8 -*-

import logging

from django_filters import rest_framework as rest_filters
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions, filters, generics
from rest_framework.pagination import PageNumberPagination
from rest_framework.authentication import SessionAuthentication, TokenAuthentication

from apps.home.models import Ticket, TicketPriority, TicketTag
from apps.authentication.models import Department
from .serializers import (
    TicketSerializer, TicketTagSerializer, TicketPrioritySerializer,
    UserSerializer
)

log = logging.getLogger(__name__)


class TicketPaginiation(PageNumberPagination):
    page_size = 25
    page_size_query_param = "page_size"
    max_page_size = 100


class TicketListApiView(generics.ListAPIView):
    """Returns a list of all **Tickets** on the system.

    Use a querystring to filter down, order, and search the results.

    Querystring options are:
    - uuid
    - priority
    - tags
    - author
    - author__department
    """

    authentication_classes = [SessionAuthentication, TokenAuthentication]
    permission_classes = [permissions.IsAuthenticated]

    pagination_class = TicketPaginiation
    serializer_class = TicketSerializer

    queryset = Ticket.objects.all()

    filter_backends = [filters.SearchFilter, rest_filters.DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ["uuid", "priority", "tags", "author", "author__department"]
    search_fields = ["author__forename", "author__surname", "title", "description"]
    ordering_fields = ["create_timestamp", "edit_timestamp"]

    def get_queryset(self):
        tag_uuids = self.request.query_params.getlist("tags", [])
        queryset = self.queryset

        log.debug("tag uuids %s", tag_uuids)

        for uuid in tag_uuids:
            if not uuid: continue
            log.debug("uuid %s", uuid)
            queryset = queryset.filter(tags__uuid__in=[uuid])

        return queryset


class FilterCountListApiView(generics.ListAPIView):
    authentication_classes = [SessionAuthentication, TokenAuthentication]
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        self._tickets = Ticket.objects.all()
        data = {"tickets": self._tickets.count()}

        self._fill_data(TicketPriority, data, "priority")
        self._fill_data(TicketTag, data, "tags")
        self._fill_data(Department, data, "department", model_key="author__department")

        return Response(data, status.HTTP_200_OK)


    def _fill_data(self, model, data: dict, key: str, *, model_key:str=None):
        data[key] = {}  # prevent KeyError
        objects = model.objects.all()
        for obj in objects:
            data[key][str(obj.uuid)] = self._tickets.filter(**{model_key or key: obj}).count()
