from rest_framework import permissions
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework import permissions, status
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication

from django.http import HttpRequest
from django.db.models import QuerySet
from django.contrib.auth.models import User

from .serializers import ProfileSerializer
from .models import ProfileModel

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = ProfileModel.objects.all
    serializer_class = ProfileSerializer
    parser_classes = (MultiPartParser, FormParser)
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def retrieve(self, request: HttpRequest, username=None):
        user = User.objects.filter(username=username)
        if (not user):
            return Response({"detail": "Profile not found."}, status=status.HTTP_404_NOT_FOUND)
        instance = self.queryset().get(pk=user[0].pk)
        instance.avatar_url.name = instance.avatar_url.name[instance.avatar_url.name.find("static") - 1:]
        return Response(self.serializer_class(instance).data,
                        status=status.HTTP_200_OK)

    def list(self, request: HttpRequest):
        serializer = ProfileSerializer(self.queryset(), many=True)
        for profile in serializer.data:
            profile["avatar_url"] = profile["avatar_url"][profile["avatar_url"].find("static") - 1:]
        return Response(serializer.data)

class MyProfileViewSet(viewsets.ModelViewSet):

    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (SessionAuthentication,)
    serializer_class = ProfileSerializer
    queryset = ProfileModel.objects.all

    def get_object(self):
        obj = self.queryset().get(pk=self.request.user.pk)
        return obj

    def perform_update(self, serializer, pk=None):
        profile: ProfileModel = self.get_object()
        avatar = self.request.data.get("file", None)
        if (avatar is not None):
            if (profile.avatar_url.name != "./profiles/static/avatars/default.avif"):
                profile.avatar_url.storage.delete(profile.avatar_url.name)
            profile.avatar_url = avatar
        profile.save()
    
    def retrieve(self, request: HttpRequest, pk=None):
        instance: ProfileModel = self.get_object()
        instance.avatar_url.name = instance.avatar_url.name[instance.avatar_url.name.find("static") - 1:]
        return Response(self.serializer_class(instance).data,
                        status=status.HTTP_200_OK)
