import logging

from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from core.mixins import ApiPermissionCheckMixin
from core.services.pagination import BasicPagination
from perms.models import Perm
from users.models import UserInfo
from users.serializers import UserInfoSerializer, UserInfoUpdateSerializer, UserSerializers
from users.services.userinfo import delete_user

LOGGER = logging.getLogger(__name__)


class NotDeletedUsersViewSet(ModelViewSet):
    """ ViewSet for handling all operations with users """

    filters = []
    serializer_class = UserInfoSerializer
    queryset = UserInfo.objects.exclude(user__username__contains='deleted')
    console_permissions = {'list': [Perm.can_view_user_list], 'create': [Perm.can_add_user],
                           'retrieve': [Perm.can_view_user], 'update': [Perm.can_edit_user],
                           'partial_update': [Perm.can_edit_user],
                           "delete": [Perm.can_delete_user]}
    pagination_class = BasicPagination

    ordering_fields = ['user__id', 'comment', 'user__username', 'user__first_name', 'user__is_active', 'user__email']

    class Meta:
        model = UserInfo

    def destroy(self, request, *args, **kwargs):
        target_user = User.objects.get(pk=kwargs['pk'])
        if request.user == target_user:
            raise ValidationError({'details': 'You cannot delete your account'})
        delete_user(user_deleting=target_user)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def get_serializer_class(self):
        if self.action == 'partial_update':
            return UserInfoUpdateSerializer
        else:
            return UserInfoSerializer

    @action(detail=False, methods=['GET'])
    def whoami(self, request, *args, **kwargs):
        user_serialize = UserSerializers(get_object_or_404(User, pk=request.user.pk))
        return Response(user_serialize.data)
