from django.db import transaction
from django.db.models import Q
from rest_framework import status
from rest_framework import viewsets, filters
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from apps.core.mixins.search_mixin import DynamicSearchMixin
from apps.core.pagination import CustomPageNumberPagination
from apps.herd.models import Rancher
from apps.pos_device.mixins.pos_device_mixin import POSDeviceMixin
from apps.product import models as product_models
from apps.product.models import OrganizationQuotaStats
from apps.product.pos.api.v1.serializers import quota_serializers
from apps.warehouse.services.services import can_buy_from_inventory


def trash(queryset, pk):  # noqa
    """ sent object to trash """
    obj = queryset.get(id=pk)
    obj.trash = True
    obj.save()


def delete(queryset, pk):
    """ full delete object """
    obj = queryset.get(id=pk)
    obj.delete()


class QuotaViewSet(viewsets.ModelViewSet, DynamicSearchMixin, POSDeviceMixin):  # noqa
    """ apis for product quota """

    queryset = product_models.Quota.objects.all()
    serializer_class = quota_serializers.QuotaSerializer
    filter_backends = [filters.SearchFilter]
    CustomPageNumberPagination.page_size = 5
    search_fields = [
        "registerer_organization__name",
        "quota_id",
        "product__name",
        "sale_type",
        "sale_unit__unit",
        "group",
    ]


class QuotaIncentiveAssignmentViewSet(viewsets.ModelViewSet):  # noqa
    """ apis for incentive assignment """

    queryset = product_models.QuotaIncentiveAssignment.objects.all()
    serializer_class = quota_serializers.QuotaIncentiveAssignmentSerializer

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota incentive assignment to trash """
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_name='delete',
        url_path='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ Full delete of quota incentive assignment object """
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)


class QuotaBrokerValueViewSet(viewsets.ModelViewSet):  # noqa
    """ apis for quota broker value """

    queryset = product_models.QuotaBrokerValue.objects.all()
    serializer_class = quota_serializers.QuotaBrokerValueSerializer

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota broker value to trash """
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_name='delete',
        url_path='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ Full delete of quota broker value object """
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)


class QuotaLiveStockAllocationViewSet(viewsets.ModelViewSet):
    """ apis for quota livestock allocation """

    queryset = product_models.QuotaLivestockAllocation.objects.all()
    serializer_class = quota_serializers.QuotaLiveStockAllocationSerializer

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota livestock allocation to trash """
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_name='delete',
        url_path='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ Full delete of quota livestock allocation object """
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)


class QuotaLiveStockAgeLimitation(viewsets.ModelViewSet):
    queryset = product_models.QuotaLiveStockAgeLimitation.objects.all()  # noqa
    serializer_class = quota_serializers.QuotaLiveStockAgeLimitationSerializer

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota livestock age limitation to trash """
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_name='delete',
        url_path='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ Full delete of quota livestock age limitation object """
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)


class OrganizationQuotaStatsViewSet(viewsets.ModelViewSet, DynamicSearchMixin, POSDeviceMixin):
    queryset = OrganizationQuotaStats.objects.all()
    serializer_class = quota_serializers.OrganizationQuotaStatsSerializer
    permission_classes = [AllowAny]
    filter_backends = [filters.SearchFilter]
    search_fields = [
        "quota__registerer_organization__name",
        "quota__quota_id",
        "quota__product__name",
        "quota__sale_type",
        "quota__sale_unit__unit",
        "quota__group",
    ]

    @action(
        methods=['get'],
        detail=False,
        url_name='rancher_quotas',
        url_path='rancher_quotas',
        name='rancher_quotas'
    )
    def rancher_distributions(self, request):
        """ list of quota distributions for rancher """

        organization = self.get_device_organization()
        device = self.get_pos_device()
        rancher = Rancher.objects.filter(national_code=request.GET['national_code'])

        # get distributions with open quota
        quotas = self.queryset.filter(
            Q(organization=organization),
            Q(quota__is_closed=False),
            Q(total_amount__gt=0),
            (
                    Q(quota__pre_sale=True) | Q(quota__free_sale=True) | Q(inventory_received__gt=0)
            )
        ).order_by('-create_date')

        # check quota distributions for rancher
        available_distributions = [
            stat for stat in quotas if (
                    can_buy_from_inventory(rancher.first(), quota_stat=stat) & rancher.exists()
            )
        ]

        # paginate & response
        page = self.paginate_queryset(available_distributions)  # noqa
        if page is not None:  # noqa
            serializer = self.get_serializer(page, many=True, context={
                'rancher': rancher.first(),
                'device': device,
                'organization': organization
            })
            # set custom message for paginator
            if not rancher:
                self.paginator.set_message("دامدار با کد ملی مد نظر یافت نشد")  # noqa
            elif not available_distributions:
                self.paginator.set_message("دامدار با کد ملی مد نظر سهمیه ایی ندارد")  # noqa
            return self.get_paginated_response(serializer.data)
