from apps.product.pos.api.v1.serializers import quota_distribution_serializers as distribution_serializers
from apps.core.mixins.search_mixin import DynamicSearchMixin
from apps.core.pagination import CustomPageNumberPagination
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.response import Response
from rest_framework.decorators import action
from rest_framework import viewsets, filters
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):
    """ quota distribution apis """

    queryset = product_models.QuotaDistribution.objects.all()
    serializer_class = distribution_serializers.QuotaDistributionSerializer
    filter_backends = [filters.SearchFilter]
    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 """

        queryset = self.filter_query(self.queryset)  # return by search param or all objects
        organization = get_organization_by_user(request.user)

        query = self.request.query_params
        if query.get('param') == 'assigned':
            # paginate queryset
            page = self.paginate_queryset(
                queryset.filter(
                    Q(assigned_organization=organization)
                ).order_by('-modify_date')
            )

        elif query.get('param') == 'assigner':
            # paginate queryset
            page = self.paginate_queryset(
                queryset.filter(
                    Q(assigner_organization=organization)
                ).order_by('-modify_date')
            )

        elif query.get('param') == 'all':
            # paginate queryset
            page = self.paginate_queryset(
                queryset.filter(
                    Q(assigner_organization=organization) |
                    Q(assigned_organization=organization)
                ).order_by('-modify_date')
            )

        if page is not None:  # noqa
            serializer = self.get_serializer(page, many=True)  # 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)
