# from rest_framework.views import APIView
from rest_framework import status, viewsets
from rest_framework.response import Response
from app.entities import enums
from app.entities.models import AllowedCompany
from app.applicationlayer.utils import CustomPagination, status_message_response
# from rest_framework.exceptions import ParseError
from django_filters import rest_framework as filters
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from app.applicationlayer.cms.allowed_company.serializer import (
    AllowedCompanySerializer
)
from app.applicationlayer.cms.allowed_company.table_filter import (
    AllowedCompanyFilterSet
)
from django.db import transaction
from rest_framework.exceptions import ValidationError
from django.db import IntegrityError


class AllowedCompanyViewSet(viewsets.ModelViewSet):
    # queryset = AllowedCompany.objects.all()
    queryset = AllowedCompany.objects.select_related(
        'id_number', 'company_pivot', 'group_pivots'
    ).all()
    serializer_class = AllowedCompanySerializer
    pagination_class = CustomPagination
    lookup_field = 'code'
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    filterset_class = AllowedCompanyFilterSet
    ordering_fields = '__all__'
    search_fields = (
        'id_number__code', 'company_pivot__code',
        'group_pivots__code'
    )

    # @decorators.rms.user_list
    def list(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        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 Users found',
                serializer.data
            )
            
            return self.get_paginated_response(message)

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

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

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        try:
            form = request.data['form']
            id_number = form[0]['id_number']
            AllowedCompany.objects.filter(id_number=id_number).delete()
            serializer = AllowedCompanySerializer(
                data=form, many=True
            )
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                message = {
                    'code': 201,
                    'status': 'success',
                    'message': 'Form Details successfully saved!',
                    'results': serializer.data
                }

                return Response(message, status=status.HTTP_201_CREATED)
        except ValidationError as e:
            message = {
                'code': 400,
                'status': 'failed',
                'message': str(e),
            }
            return Response(message, status=status.HTTP_400_BAD_REQUEST)

        except IntegrityError as e:
            error = 'Adding the same Department under the same Company is not allowed'
            message = {
                'code': 400,
                'status': 'failed',
                'message': error,
            }
            return Response(message,
                            status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            message = {
                'code': 500,
                'status': 'failed',
                'message': str(e),
            }
            return Response(message,
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
