from apps.herd.pos.api.v1.serializers import HerdSerializer, RancherSerializer
from apps.livestock.web.api.v1.serializers import LiveStockSerializer
from apps.core.mixins.search_mixin import DynamicSearchMixin
from rest_framework.exceptions import APIException
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.decorators import action
from common.tools import CustomOperations
from rest_framework import viewsets
from apps.herd.models import Herd, Rancher
from django.db import transaction
from rest_framework import status


class HerdViewSet(viewsets.ModelViewSet):
    """ Herd ViewSet """

    queryset = Herd.objects.all()
    serializer_class = HerdSerializer
    permission_classes = [AllowAny]

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        """ create herd with user """

        if 'rancher' in request.data.keys():
            rancher = CustomOperations().custom_create(
                request=request,
                view=RancherViewSet(),
                data=request.data['rancher']
            )
            request.data.update({'rancher': rancher['id']})

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

    @action(
        methods=['get'],
        detail=False,
        url_name='my_herds',
        url_path='my_herds',
        name='my_herds'
    )
    @transaction.atomic
    def my_herds(self, request):
        """ get current user herds """
        serializer = self.serializer_class(self.queryset.filter(owner=request.user.id), many=True)
        if serializer.data:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(status=status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash'
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent herd to trash """
        try:
            herd = self.queryset.get(id=pk)
            herd.trash = True
            herd.save()
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_path='delete',
        url_name='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ full delete of herd """
        try:
            herd = self.queryset.get(id=pk)
            herd.delete()
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)

    @action(
        methods=['get'],
        detail=True,
        url_path='live_stocks',
        url_name='live_stocks',
        name='live_stocks'
    )
    def live_stocks(self, request, pk=None):
        """ list of herd live_stocks"""

        herd = self.get_object()
        queryset = herd.live_stock_herd.all()  # get herd live_stocks

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


class RancherViewSet(viewsets.ModelViewSet, DynamicSearchMixin):
    queryset = Rancher.objects.all()  # noqa
    serializer_class = RancherSerializer
    permission_classes = [AllowAny]
    search_fields = [
        "ranching_farm",
        "first_name",
        "last_name",
        "mobile",
        "national_code",
        "birthdate",
        "nationality",
        "address",
        "province__name",
        "city__name",
    ]

    @action(
        methods=['post'],
        detail=False,
        url_name='check_national_code',
        url_path='check_national_code',
        name='check_national_code'
    )
    @transaction.atomic
    def check_national_code(self, request):
        """ check national code & existence of rancher """

        rancher = self.queryset.filter(national_code=request.data['national_code'])

        if rancher.exists():
            serializer = self.serializer_class(rancher.first())
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response({
                "message": "rancher has not existence"
            }, status=status.HTTP_403_FORBIDDEN)
