from rest_framework import viewsets, status
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.response import Response

import asset.gtin_service
from api.serializers import ContainerSerializer, ContainerTypeSerializer, AssetSerializer, GtinProductSerializer
from container.models import Container, ContainerType
from asset.models import Asset, GtinProduct


class ContainerViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows containers to be viewed or edited.
    """
    queryset = Container.objects.all().order_by('named_id')
    serializer_class = ContainerSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['named_id', 'color']


class ContainerTypeViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows container-types to be viewed or edited.
    """
    queryset = ContainerType.objects.all()
    serializer_class = ContainerTypeSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['named_id', 'has_cover', 'contains_container']


class AssetViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows containers to be viewed or edited.
    """
    queryset = Asset.objects.all().order_by('named_id')
    serializer_class = AssetSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['named_id', 'quantity']


class GtinProductViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows containers to be viewed or edited.
    """
    queryset = GtinProduct.objects.all().order_by('gtin')
    serializer_class = GtinProductSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['gtin']

    def retrieve(self, request, pk=None):
        if pk:
            item = GtinProduct.objects.get(id=pk)
            serializer = GtinProductSerializer(item)
            return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)

        items = GtinProduct.objects.all()
        serializer = GtinProductSerializer(items, many=True)
        return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)

    @action(detail=True, methods=['GET'])
    def by_gtin(self, request, gtin=None):
        if gtin:
            item = asset.gtin_service.get_by_gtin(gtin=gtin)
            if item:
                serializer = GtinProductSerializer(item)
                return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
            return Response(
                {"status": "failed", "reason": "Could not find a product for given GTIN", "gtin": gtin},
                status=status.HTTP_404_NOT_FOUND)
        return Response({"status": "failed", "reason": "No GTIN given, please provide a valid GTIN"},
                        status=status.HTTP_400_BAD_REQUEST)
