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.response import Response

from apps.core.api import BaseViewSet
from apps.core.mixins.search_mixin import DynamicSearchMixin
from apps.core.mixins.soft_delete_mixin import SoftDeleteMixin
from apps.core.pagination import CustomPageNumberPagination
from apps.product import exceptions
from apps.product import models as product_models
from apps.product.web.api.v1.serializers import quota_distribution_serializers as distribution_serializers
from common.helpers import get_organization_by_user


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(BaseViewSet, SoftDeleteMixin, 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"

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        """ create distribution for organizations users """

        organization = get_organization_by_user(request.user)
        # get distributed assigner user
        try:
            assigner_user = product_models.UserRelations.objects.filter(
                user=request.user
            ).first()
        except APIException as e:
            raise APIException("unauthorized", code=status.HTTP_401_UNAUTHORIZED)

        price_attributes_data = request.data.pop(
            'price_attributes_data'
        ) if 'price_attributes_data' in request.data.keys() else None

        broker_data = request.data.pop(
            'broker_data'
        ) if 'broker_data' in request.data.keys() else None

        request.data.update({'assigner_organization': assigner_user.organization.id})
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            distribution = serializer.save()

            # add this organization to quota assigned_organizations
            # this org is received a distribution from quota
            distribution.quota.assigned_organizations.add(distribution.assigned_organization)

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def update(self, request, *args, **kwargs):
        """ Custom update of quota distribution """

        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)

    @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 """

        query = self.request.query_params  # noqa
        organization = get_organization_by_user(request.user)
        if organization.free_visibility_by_scope:
            queryset = self.filter_query(self.get_queryset(visibility_by_org_scope=True))
        else:
            queryset = self.filter_query(self.get_queryset())  # return by search param or all objects  # noqa
            if query.get('param') == 'assigned':
                queryset = queryset.filter(
                    Q(assigned_organization=organization)
                ).order_by('-modify_date')

            elif query.get('param') == 'assigner':
                queryset = queryset.filter(
                    Q(assigner_organization=organization)
                ).order_by('-modify_date')

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

        if query.get('archive') and query.get('archive') == 'true':
            queryset = queryset.filter(Q(quota__is_closed=True))
        else:
            queryset = queryset.filter(Q(quota__is_closed=False))

        if query.get('product_id'):
            queryset = queryset.filter(Q(quota__product_id=int(query.get('product_id'))))

        queryset = self.filter_query(self.filter_queryset(queryset))

        page = self.paginate_queryset(queryset)
        if page is not None:  # noqa
            serializer = self.get_serializer(page, many=True)  # noqa
            return self.get_paginated_response(serializer.data)

    @action(
        methods=['get'],
        detail=False,
        url_name='quota_distributions_assigned_by_org',
        url_path='quota_distributions_assigned_by_org',
        name='quota_distributions_assigned_by_org'
    )
    def quota_distributions_assigned_by_org(self, request):
        """
        list of distributions pf a quota that target org is assigner
        """
        query = self.request.query_params  # noqa

        target_org = product_models.Organization.objects.filter(
            id=query.get('org_id')
        ).first()

        target_quota = product_models.Quota.objects.filter(
            id=query.get('quota_id')
        ).first()

        queryset = self.filter_query(self.get_queryset().filter(
            assigner_organization=target_org,
            quota=target_quota
        ))

        page = self.paginate_queryset(queryset)
        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() or self.queryset.filter(
                parent_distribution=quota_distribution.id
        ):
            raise exceptions.DistributionDeletedException()
        try:
            trash(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except Exception as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)
