
#  ویوست و توابعی که برای ایجاد سطج دستزسی جدید در سیستم استفاده میشوند


from django.contrib.auth.models import Group
from oauth2_provider.contrib.rest_framework import TokenHasScope, TokenHasReadWriteScope
from rest_framework import viewsets, serializers, status
from rest_framework.permissions import IsAuthenticated
from . import permissions
from rest_framework.response import Response
import logging

log = logging.getLogger(__name__)


class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ['name']


class GroupPermissionViewset(viewsets.ModelViewSet):
    authentication_classes = []
    permission_classes = [TokenHasReadWriteScope]
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

    def get_queryset(self):
        queryset = super(GroupPermissionViewset, self).get_queryset()
        log.error(f"here {self.request.user}")

        return queryset

    def list(self, request, *args, **kwargs):
        queryset = super(GroupPermissionViewset, self).get_queryset()
        log.error(f"here {request.user}")

        serializer = GroupSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.create(validated_data=request.data)
            return Response(serializer.data)
        return Response(serializer.errors)

    def retrieve(self, request, pk=None, *args, **kwargs):
        key = request.GET['name']
        log.error(f"here {request.user}")
        queryset = super(GroupPermissionViewset, self).get_queryset()

        queryset = queryset.get(name__exact=key)
        serializer = self.serializer_class(queryset)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        key = request.GET['name']
        queryset = super(GroupPermissionViewset, self).get_queryset()
        queryset = queryset.get(name__exact=key)
        serializer = self.serializer_class(queryset)
        serializer.update(instance=queryset, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def partial_update(self, request, pk=None, *args, **kwargs):
        pass

    def destroy(self, request, pk=None, *args, **kwargs):
        key = request.GET['name']
        queryset = super(GroupPermissionViewset, self).get_queryset()

        queryset = queryset.get(name__exact=key)
        queryset.delete()
        queryset.save()
        return Response(status=status.HTTP_200_OK)
