from rest_framework import viewsets, status
from rest_framework.response import Response
from app.entities.models import ChangeRequestTemplateHeader, AllowedCompany
from app.applicationlayer.cms.master.template_list.serializers import ChangeRequestTemplatesSerializer
from app.applicationlayer.utils import CustomPagination, status_message_response
from rest_framework.exceptions import ParseError
from django.db.models import Q


class ChangeRequestTemplateHeaderMaster(viewsets.ModelViewSet):
    queryset = ChangeRequestTemplateHeader.objects.all()
    serializer_class = ChangeRequestTemplatesSerializer
    pagination_class = CustomPagination
    lookup_field = 'template_no'

    def list(self, request, *args, **kwargs):
        if "department_code" not in request.query_params:
           raise ParseError('department_code is expected at query params')

        department = request.query_params['department_code']

        permit = AllowedCompany.objects.filter(
            group_pivots=department
        ).count()

        if permit <= 0:
            raise ParseError('This department is not allowed')
        else:

            queryset = ChangeRequestTemplateHeader.objects.filter(
                requested_to_department=department, is_active=True
            )

            included = AllowedCompany.objects.filter(
                Q(id_number=request.user.code) &
                Q(create_change_request=True)
            ).values('group_pivots')

            queryset = queryset.filter(
                requested_to_department__in=included
            ).order_by('requested_to_template_name')

        page = self.paginate_queryset(queryset)

        if page is not None:
            serializer = self.get_serializer(page, many=True)

            message = status_message_response(
                200,
                'success',
                'List of Templates found',
                serializer.data
            )

            return self.get_paginated_response(message)

        serializer = self.get_serializer(self.queryset, many=True)

        return Response(
            serializer.data,
            status=status.HTTP_200_OK
        ) 
