from drf_spectacular.utils import extend_schema

from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.utils.translation import gettext

from rest_framework.exceptions import NotFound
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response

from lms.core.views.viewsets import APIModelViewSet

from ..serializers import (
    PermissionListCodenameSerializer, UserCreateSerializer, UserDetailSerializer, UserUpdateSerializer,
)

User = get_user_model()


class BaseUserViewSet(APIModelViewSet):
    queryset = User.objects.none()
    serializer_class = UserDetailSerializer
    serializer_classes = {
        'create': UserCreateSerializer,
        'update': UserUpdateSerializer,
        'partial_update': UserUpdateSerializer,
    }

    def get_object(self):
        user = getattr(self.request, 'user', None)
        tvm_uid = self.get_tvm_uid()
        if not user.is_authenticated:
            # возвращаем 404, если профиль не существует
            if tvm_uid is not None:
                if not User.objects.filter(yauid=tvm_uid).exists():
                    raise NotFound()

            return self.permission_denied(self.request, 'Not Authenticated')

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

        return user

    @extend_schema(
        summary=gettext("Информация о профиле")
    )
    def retrieve(self, request, *args, **kwargs):
        return super().retrieve(request, *args, **kwargs)

    @extend_schema(
        summary=gettext("Добавление профиля пользователя"),
        responses={201: UserDetailSerializer},
    )
    def create(self, request, *args, **kwargs):
        tvm_uid = self.get_tvm_uid()
        if not tvm_uid:
            self.permission_denied(request, 'No user ticket provided')

        return super().create(request, *args, **kwargs)

    def perform_create(self, serializer):
        tvm_uid = self.get_tvm_uid()
        unusable_password = make_password(None)
        serializer.save(yauid=tvm_uid, password=unusable_password)

    @extend_schema(
        summary=gettext("Обновление данных профиля"),
        responses={200: UserDetailSerializer},
    )
    def update(self, request, *args, **kwargs):
        return super().update(request, *args, **kwargs)

    @extend_schema(
        summary=gettext("Обновление данных профиля"),
        responses={200: UserDetailSerializer},
    )
    def partial_update(self, request, *args, **kwargs):
        return super().partial_update(request, *args, **kwargs)


class UserViewSet(BaseUserViewSet):
    permission_classes = [
        AllowAny,
    ]


class BaseUserPermissionsViewSet(APIModelViewSet):
    serializer_class = PermissionListCodenameSerializer
    pagination_class = None
    permission_classes = [
        IsAuthenticated,
    ]
    queryset = User.objects.none()

    @extend_schema(
        summary=gettext("Список разрешений пользователя"),
        responses={
            200: PermissionListCodenameSerializer,
        },
    )
    def list(self, *args, **kwargs):
        user = getattr(self.request, 'user')
        serializer = self.get_serializer(user.get_all_permissions())
        return Response(serializer.data)


class UserPermissionsViewSet(BaseUserPermissionsViewSet):
    pass
