from django.shortcuts import get_object_or_404
from rest_framework import viewsets, permissions
from rest_framework.response import Response

from webservice_running.models import OrdersLocal
from webservice_running.serializer import OrdersLocalSerializer


# from dbsynce.models import Orders, Service, ServiceCategory, Provider, Client
# from sharix_admin.models import SharixUser
# from tickets.models import Task
# from tickets.serializer import TaskSerializer

class OrdersLocalMVS(viewsets.ModelViewSet):
    queryset = OrdersLocal.objects.all()
    serializer_class = OrdersLocalSerializer
    # permission_classes = [IsOwnerOrReadOnly]
    permission_classes = [
        permissions.IsAuthenticated
    ]

    def get_object(self):
        """
        Returns the object the view is displaying.

        You may want to override this if you need to provide non-standard
        queryset lookups.  Eg if objects are referenced using multiple
        keyword arguments in the url conf.
        """
        # queryset = self.filter_queryset(self.get_queryset())
        queryset = OrdersLocal.objects.select_related('order_synced__ticket')

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        assert lookup_url_kwarg in self.kwargs, (
                'Expected view %s to be called with a URL keyword argument '
                'named "%s". Fix your URL conf, or set the `.lookup_field` '
                'attribute on the view correctly.' %
                (self.__class__.__name__, lookup_url_kwarg)
        )

        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()  # OrdersLocal.objects.select_related('order_synced__ticket').get(id=1)
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        # for serializer in serializers:
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)
