from apps.product.pos.api.v1.serializers import quota_distribution_serializers as distribution_serializers
from apps.pos_device.mixins.pos_device_mixin import POSDeviceMixin
from apps.core.mixins.search_mixin import DynamicSearchMixin
from apps.core.pagination import CustomPageNumberPagination
from apps.warehouse.services.services import can_buy_from_inventory
from common.helpers import get_organization_by_user
from rest_framework.exceptions import APIException
from apps.product import models as product_models
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework import viewsets, filters
from apps.herd.models import Rancher
from rest_framework import status
from django.db import transaction
from django.db.models import Q


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 QuotaDistributionViewSet(viewsets.ModelViewSet, DynamicSearchMixin, POSDeviceMixin):
    """ quota distribution apis """

    queryset = product_models.QuotaDistribution.objects.all()
    serializer_class = distribution_serializers.QuotaDistributionSerializer
    permission_classes = [AllowAny]
    CustomPageNumberPagination.page_size = 5
    search_fields = [
        "assigner_organization__name",
        "assigned_organization__name",
        "distribution_id",
        "quota__quota_id",
        "quota__product__name",
        "quota__sale_type",
        "quota__group",
    ]
    date_field = "create_date"

    @action(
        methods=['get'],
        detail=False,
        url_name='my_distributions',
        url_path='my_distributions',
        name='my_distributions'
    )
    def my_distributions(self, request):
        """ list of my distributions """

        organization = self.get_device_organization()
        device = self.get_pos_device()

        # get distributions with open quota
        distributions = self.queryset.filter(
            assigned_organization=organization,
            quota__is_closed=False,
            warehouse_entry__gt=0
        ).order_by('-create_date')

        queryset = self.filter_query(distributions)  # return by search param or all objects

        # paginate & response
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True, context={'device': device})
            return self.get_paginated_response(serializer.data)

    @action(
        methods=['get'],
        detail=False,
        url_name='rancher_distributions',
        url_path='rancher_distributions',
        name='rancher_distributions'
    )
    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
        distributions = self.queryset.filter(
            assigned_organization=organization,
            quota__is_closed=False,
            warehouse_entry__gt=0
        ).order_by('-create_date')

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

        # paginate & response
        page = self.paginate_queryset(available_distributions)  # noqa
        if page is not None:
            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)

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota distribution to trash """
        quota_distribution = self.get_object()

        # check if distribution has inventory entry
        if quota_distribution.inventory_entry.exists():
            raise APIException(
                "امکان حذف این توزیع وجود ندارد. ورود به انبار برای آن ثبت شده است",  # noqa
                status.HTTP_400_BAD_REQUEST
            )
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def destroy(self, request, pk=None, *args, **kwargs):
        """ Full delete of quota distribution object """

        quota_distribution = self.get_object()

        # check if distribution has inventory entry
        if quota_distribution.inventory_entry.exists():
            raise APIException(
                "امکان حذف این توزیع وجود ندارد. ورود به انبار برای آن ثبت شده است",  # noqa
                status.HTTP_400_BAD_REQUEST
            )
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except Exception as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)
