# -*- 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):
    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 FilterCountApiView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    @method_decorator(cache_page(60 * 5))
    def get(self, request):

        priorities = TicketPriority.objects.all()
        tags = TicketTag.objects.all()
        departments = Department.objects.all()

        tickets = Ticket.objects.all()

        data = {
            "priority_counts": {},
            "tag_counts": {},
            "department_counts": {},
            "ticket_count": tickets.count()
        }

        for priority in priorities:
            data["priority_counts"][str(priority.uuid)] = tickets.filter(priority=priority).count()

        for tag in tags:
            data["tag_counts"][str(tag.uuid)] = tickets.filter(tags__in=[tag]).count()

        for department in departments:
            data["department_counts"][str(department.uuid)] = tickets.filter(author__department=department).count()

        return Response(data, status=status.HTTP_200_OK)
