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
from app.applicationlayer.utils import (
    CustomPagination, status_message_response
)

from django_filters.rest_framework import DjangoFilterBackend
from app.applicationlayer.master.Account import serializer
from app.applicationlayer.management.account.table_filters import AccountFilterset
from app.helper.decorators import rms
from django.db.models import Q


class AdminAccountViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all().order_by('-id')
    serializer_class = serializer.AdminAccountSerializer
    pagination_class = CustomPagination
    lookup_field = 'code'
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    filterset_class = AccountFilterset
    ordering_fields = '__all__'
    search_fields = (
        'name', 'company__name', 'code', 'department__name',
        'email', 'contact_no',
    )

    # @rms.department_list
    def list(self, request, *args, **kwargs):
        try:

            queryset = self.filter_queryset(self.get_queryset())
            if len(self.request.query_params) > 0:
                dept = self.request.query_params['department_code']
                company = self.request.query_params['company_code']
                queryset = queryset.filter(
                    Q(department__company=company) &
                    Q(department=dept)
                )
                queryset = queryset.exclude(id=1)
            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 User found',
                    serializer.data
                )
                return self.get_paginated_response(message)

            serializer = self.get_serializer(queryset, many=True)
            return Response(serializer.data)
        except Exception as e:
            return Response(
                {'message': "query params department_code and company_code are both expected"},
                status=status.HTTP_400_BAD_REQUEST
            )
