from apps.herd.web.api.v1.serializers import HerdSerializer
from apps.authentication.api.v1.api import UserViewSet
from rest_framework.exceptions import APIException
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
from django.db import transaction
from rest_framework import status


class HerdViewSet(viewsets.ModelViewSet):
    """ Herd ViewSet """
    queryset = Herd.objects.all()
    serializer_class = HerdSerializer

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        """ create herd with user """
        if 'user' in request.data.keys():
            #  create user if owner of herd is not exist
            user = CustomOperations().custom_create(
                request=request,
                view=UserViewSet(),
                data_key='user'
            )
            owner = user['id']
            request.data.update({'owner': owner})

        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)
