from rest_framework import viewsets, status
from rest_framework.response import Response
from app.applicationlayer.utils import model_to_dict
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters import rest_framework as filters
from app.entities.models import User, AllowedCompany
from app.applicationlayer.utils import (
    CustomPagination, status_message_response
)

from django_filters.rest_framework import DjangoFilterBackend
from app.applicationlayer.cms.master.template.default_approver import serializer
from app.applicationlayer.cms.master.template.default_approver.table_filter import (
    DefaultApproverFilterSet
)
from app.helper.decorators import rms
from django.db.models import Q
from rest_framework.exceptions import ParseError


class DefaultApproverViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = serializer.DefaultApproverSerializer
    pagination_class = CustomPagination
    lookup_field = 'code'
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    filterset_class = DefaultApproverFilterSet
    ordering_fields = '__all__'
    search_fields = ('name', 'department__name', 'code')
    
    def list(self, request, *args, **kwargs):
        department = self.request.query_params['department_code']
        queryset = self.filter_queryset(self.get_queryset())
        default_user = AllowedCompany.objects.filter(
            Q(group_pivots=department) &
            Q(approve_cr=True)
        ).values('id_number')
        queryset = queryset.filter(code__in=default_user)
        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 Default Approvers found',
                serializer.data
            )
            return self.get_paginated_response(message)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
