from apps.warehouse.pos.api.v1 import serializers as warehouse_serializers
from apps.warehouse.services.services import (
    can_buy_from_inventory,
    rancher_quota_weight,
    get_rancher_statistics
)
from apps.pos_device.mixins.pos_device_mixin import POSDeviceMixin
from apps.core.mixins.search_mixin import DynamicSearchMixin
from apps.warehouse import models as warehouse_models
from rest_framework.permissions import AllowAny
from rest_framework.decorators import action
from rest_framework import viewsets
from apps.herd.models import Rancher
from django.db import transaction


class InventoryEntryViewSet(viewsets.ModelViewSet, DynamicSearchMixin, POSDeviceMixin):
    queryset = warehouse_models.InventoryEntry.objects.all()
    serializer_class = warehouse_serializers.InventoryEntrySerializer
    permission_classes = [AllowAny]
    search_fields = [
        "distribution__distribution_id",
        "organization__name",
        "weight",
        "balance",
        "lading_number",
        "is_confirmed",
    ]
    date_field = "create_date"

    @action(
        methods=['get'],
        detail=False,
        url_path='my_entries',
        url_name='my_entries',
        name='my_entries'
    )
    def inventory_entries(self, request):
        """ list of pos inventory entries """

        organization = self.get_device_organization()

        entries = self.queryset.filter(organization=organization)
        queryset = self.filter_query(entries)  # 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)
            return self.get_paginated_response(serializer.data)

    @action(
        methods=['get'],
        detail=False,
        url_path='rancher_inventory_entries',
        url_name='rancher_inventory_entries',
        name='rancher_inventory_entries'
    )
    @transaction.atomic
    def rancher_inventory_entries(self, request):
        """ """
        organization = self.get_device_organization()
        rancher = Rancher.objects.filter(national_code=request.GET['national_code']).first()
        entries = self.queryset.filter(organization=organization)

        available_entries = [entry for entry in entries if can_buy_from_inventory(rancher, entry)]

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


class InventoryQuotaSaleTransactionViewSet(viewsets.ModelViewSet, DynamicSearchMixin, POSDeviceMixin):
    queryset = warehouse_models.InventoryQuotaSaleTransaction.objects.all()
    serializer_class = warehouse_serializers.InventoryQuotaSaleTransactionSerializer
    permission_classes = [AllowAny]
    search_fields = [
        "rancher__union_name",
        "rancher__union_code",
        "rancher__first_name",
        "rancher__last_name",
        "rancher__national_code",
        "pos_device__device_identity",
        "pos_device__serial",
        "transaction_id",
        "seller_organization__name",
        "quota_distribution__distribution_id",
        "inventory_entry__distribution__distribution_id",
        "product__name",
        "transaction_status",
    ]
    date_field = "create_date"

    @action(
        methods=['get'],
        detail=False,
        url_path='transactions',
        url_name='transactions',
        name='transactions',
    )
    @transaction.atomic
    def transactions(self, request):
        """ pos transactions list """

        # get device object
        device = self.get_pos_device()

        queryset = self.queryset.filter(pos_device=device)
        queryset = self.filter_query(queryset)

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