from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters import rest_framework as filters
from app.entities.models import (
    Company, AllowedCompany,
    ChangeRequestFormHeader, AllowedCompany
)
from rest_framework import viewsets, status
from app.businesslayer.company.serializer import AdminCompanySerializer
from app.applicationlayer.utils import CustomPagination, status_message_response
from django_filters.rest_framework import DjangoFilterBackend
from app.applicationlayer.management.company import serializer
from app.applicationlayer.cms.master.form.company.table_filters import (
    ChangeRequestCompanyFilterSet
)
from app.helper.decorators import rms
from rest_framework.response import Response
from django.db.models import Q
from rest_framework.decorators import action


class ChangeRequestCompanyFormViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    serializer_class = AdminCompanySerializer
    pagination_class = CustomPagination
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    filterset_class = ChangeRequestCompanyFilterSet
    ordering_fields = '__all__'
    search_fields = ('name',)
    http_method_names = ['get']

    def list(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        allowed = AllowedCompany.objects.filter(
            Q(id_number=self.request.user.code) &
            Q(create_change_request=True)
        ).values('company_pivot')
        queryset = queryset.filter(code__in=allowed)
        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 Company found',
                serializer.data
            )
            return self.get_paginated_response(message)

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


    @action(
        methods=['GET'], detail=False,
        url_path='filter', url_name='filter'
    )
    def filter(self, request, *args, **kwargs):

        # instance = self.get_object()
        # list_his = []

        queryset = self.filter_queryset(self.get_queryset())


        id_number = request.user.code

        forms = ChangeRequestFormHeader.objects.filter(
            Q(frm_approvers__user__code=id_number) |
            Q(requested_by_user=id_number) |
            Q(frm_stakes__user__code=id_number)
        ).values()
        
        allowed = AllowedCompany.objects.filter(
            id_number=id_number
        ).values().distinct()

        forms = [data['requested_to_company_id'] for data in forms]
        allowed = [data['company_pivot_id'] for data in allowed]

        forms = forms + allowed
        if len(forms) == 0:
            queryset = queryset.filter(id=0)
        else:
            queryset = queryset.filter(code__in=forms)
    
        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 Company found',
                serializer.data
            )
            return self.get_paginated_response(message)

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