from apps.pos_device.web.api.v1.serilaizers import client as client_serializer
from apps.core.mixins.soft_delete_mixin import SoftDeleteMixin
from apps.pos_device import models as pos_models
from rest_framework.response import Response
from common.tools import CustomOperations
from rest_framework import viewsets
from rest_framework import status


class POSClientViewSet(SoftDeleteMixin, viewsets.ModelViewSet):
    queryset = pos_models.POSClient.objects.all()
    serializer_class = client_serializer.POSClientSerializer

    def create(self, request, *args, **kwargs):
        """ Custom create of pos client """

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

            # create attributes with value for client
            attr_values_list = []
            if 'attribute_values' in request.data.keys():
                for attr in request.data['attribute_values']:
                    attr.update({'client': client.id})
                    attr_value = CustomOperations().custom_create(
                        request=request,
                        view=POSClientAttributeValueViewSet(),
                        data=attr
                    )
                    attr_values_list.append(attr_value)

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

    def update(self, request, pk=None, *args, **kwargs):
        """ Custom update of pos client """

        serializer = self.serializer_class(instance=self.get_object(), data=request.data)
        if serializer.is_valid():
            client = serializer.save()

            if 'attribute_values' in request.data.keys():

                # remove attribute relations from client
                client.attribute_values.all().delete()

                # create new relations
                attr_values_list = []
                for attr in request.data['attribute_values']:
                    attr.update({'client': client.id})
                    attr_value = CustomOperations().custom_create(
                        request=request,
                        view=POSClientAttributeValueViewSet,
                        data=attr
                    )
                    attr_values_list.append(attr_value)

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


class POSClientAttributeViewSet(SoftDeleteMixin, viewsets.ModelViewSet):
    queryset = pos_models.POSClientAttribute.objects.all()
    serializer_class = client_serializer.POSClientAttributeSerializer


class POSClientAttributeValueViewSet(SoftDeleteMixin, viewsets.ModelViewSet):
    queryset = pos_models.POSClientAttributeValue.objects.all()
    serializer_class = client_serializer.POSClientAttributeValueSerializer
