from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from LiveStock.Contractor.filterset import ContractorFilterSet
from LiveStock.Contractor.serializers import ContractorSerializer

from LiveStock.helpers import build_query, CustomPagination
from LiveStock.models import Contractor
from authentication.models import SystemUserProfile


class ContractorViewSet(viewsets.ModelViewSet):
    queryset = Contractor.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = ContractorSerializer
    filterset_class = ContractorFilterSet
    pagination_class = CustomPagination

    def retrieve(self, request, pk=None, *args, **kwargs):
        if 'profile' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)

            union = user.contractor_user.all()

            serializer = self.serializer_class(union[0])
            return Response(serializer.data, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        contractor = Contractor.objects.filter(trash=False).order_by('id')
        value = request.GET.get('value')
        search = request.GET.get('search')
        if value and search == 'filter':
            if search != 'undefined' and search.strip():
                contractor = contractor.filter(
                    build_query(self.filterset_class.Meta.fields, value)
                )
        page = self.paginate_queryset(contractor)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.serializer_class(contractor, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        contractor = Contractor.objects.get(key=request.data['key'], trash=False)
        request.data.pop('key')

        serializer = self.serializer_class(contractor)

        serializer.update(instance=contractor, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        contractor = Contractor.objects.get(key=request.GET["key"])
        contractor.trash = True
        contractor.save()
        return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
