import datetime
from apps.product.web.api.v1.serializers import product_serializers as product_serializers
from apps.product.web.api.v1.serializers import quota_serializers
from apps.core.mixins.soft_delete_mixin import SoftDeleteMixin
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
from datetime import datetime


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 ProductCategoryViewSet(viewsets.ModelViewSet, SoftDeleteMixin):
    queryset = product_models.ProductCategory.objects.all()
    serializer_class = product_serializers.ProductCategorySerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['type', 'name']

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent product 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 product 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 ProductViewSet(viewsets.ModelViewSet, SoftDeleteMixin):
    queryset = product_models.Product.objects.all()
    serializer_class = product_serializers.ProductSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['type', 'name']

    def list(self, request, *args, **kwargs):
        """ custom list view """  #

        queryset = self.filter_queryset(self.get_queryset().order_by('-create_date'))  # noqa

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

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    @action(
        methods=['get'],
        detail=True,
        url_path='related_quotas',
        url_name='related_quotas',
        name='related_quotas'
    )
    @transaction.atomic()
    def my_related_quotas_by_product(self, request, pk=None):
        """ quotas that related to my organization and product """

        organization = get_organization_by_user(request.user)
        quota = product_models.Quota.objects.filter(
            Q(
                distributions_assigned__in=product_models.QuotaDistribution.objects.filter(
                    Q(assigned_organization=organization) |
                    Q(assigner_organization=organization)
                )
            ) |
            Q(registerer_organization=organization),
            product=self.get_object()
        ).distinct()

        page = self.paginate_queryset(quota)
        if page is not None:
            serializer = quota_serializers.QuotaSerializer(page, many=True)
            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 product 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 product 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 ProductStatsViewSet(viewsets.ModelViewSet, SoftDeleteMixin):
    """ product statistics by its quotas """

    queryset = product_models.ProductStats.objects.all()
    serializer_class = product_serializers.ProductStatsSerializer

    @action(
        methods=['get'],
        detail=False,
        url_path='my_products_stat',
        url_name='my_products_stat',
        name='my_products_stat'
    )
    def my_products_stat(self, request):
        """ my organization products with statistics """

        try:
            organization = get_organization_by_user(request.user)
            product_stats = self.queryset.filter(organization=organization).order_by('-modify_date')

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

            serializer = self.serializer_class(product_stats, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except APIException as e:
            raise e


class AttributeViewSet(viewsets.ModelViewSet, SoftDeleteMixin):
    """ attributes of reference product """  #

    queryset = product_models.Attribute.objects.select_related('product').all()
    serializer_class = product_serializers.AttributeSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['name']

    @action(
        methods=['get'],
        detail=True,
        url_path='by_product',
        url_name='by_product',
        name='by_product'
    )
    def get_attributes_by_product(self, request, pk=None):
        """ get attributes by product with global ones """

        attributes = self.queryset.filter(Q(is_global=True) | Q(product__id=pk))

        # paginate data
        page = self.paginate_queryset(attributes)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            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 attribute 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 attribute 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 AttributeValueViewSet(viewsets.ModelViewSet, SoftDeleteMixin):
    """ apis for attribute values of child products """  # noqa

    queryset = product_models.AttributeValue.objects.all()
    serializer_class = product_serializers.AttributeValueSerializer

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent attribute 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 attribute 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 BrokerViewSet(viewsets.ModelViewSet, SoftDeleteMixin):
    """ apis of product brokers """  # noqa

    queryset = product_models.Broker.objects.all()
    serializer_class = product_serializers.BrokerSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['broker_type', 'name']

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent broker 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 broker 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 SaleUnitViewSet(viewsets.ModelViewSet, SoftDeleteMixin):
    """ apis of unit of sale for products """  # noqa

    queryset = product_models.SaleUnit.objects.all()
    serializer_class = product_serializers.SaleUnitSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['unit']

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent unit sale 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 unit sale 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 IncentivePlanViewSet(viewsets.ModelViewSet, SoftDeleteMixin):  # noqa
    """ apis for incentive plan """

    queryset = product_models.IncentivePlan.objects.all()
    serializer_class = product_serializers.IncentivePlanSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['plan_type', 'name']

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        """ custom incentive plan create object """

        # set incentive plans with user relations like organization
        user_relation = product_models.UserRelations.objects.filter(user=request.user).first()
        request.data['registering_organization'] = user_relation.id

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()

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

    @transaction.atomic
    def list(self, request, *args, **kwargs):
        """ get incentive plans by user relations like organization """

        user_relations = product_models.UserRelations.objects.filter(user=request.user).first()
        incentive_plans = user_relations.incentive_plans.all()

        serializer = self.serializer_class(incentive_plans, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(
        methods=['get'],
        detail=False,
        url_path='active_plans',
        url_name='active_plans',
        name='active_plans'
    )
    @transaction.atomic
    def active_plans(self, request):
        """ return active incentive plans """

        today = datetime.now().date()
        user_relations = product_models.UserRelations.objects.filter(user=request.user).first()
        incentive_plans = user_relations.incentive_plans.filter(
            Q(is_time_unlimited=False) |
            Q(start_date_limit__lte=today, end_date_limit__gte=today)
        )
        page = self.paginate_queryset(incentive_plans)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.serializer_class(incentive_plans, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent incentive plan 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 incentive plan 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)
