from logging import getLogger

from rest_framework import permissions, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from scrobbles.api.filters import ScrobbleFilter
from scrobbles.api.serializers import (
    AudioScrobblerTSVImportSerializer,
    KoReaderImportSerializer,
    LastFmImportSerializer,
    ScrobbleSerializer,
)
from scrobbles.models import (
    AudioScrobblerTSVImport,
    KoReaderImport,
    Scrobble,
    LastFmImport,
)

logger = getLogger(__name__)


class ScrobbleViewSet(viewsets.ModelViewSet):
    queryset = Scrobble.objects.all().order_by("-timestamp")
    serializer_class = ScrobbleSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_class = ScrobbleFilter

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)

    @action(detail=True, methods=["post"])
    def regenerate_share_token(self, request, **kwargs):
        scrobble = self.get_object()
        scrobble.regenerate_share_token()
        return Response({"share_url": scrobble.get_share_url()})


class KoReaderImportViewSet(viewsets.ModelViewSet):
    queryset = KoReaderImport.objects.all().order_by("-created")
    serializer_class = KoReaderImportSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)


class AudioScrobblerTSVImportViewSet(viewsets.ModelViewSet):
    queryset = AudioScrobblerTSVImport.objects.all().order_by("-created")
    serializer_class = AudioScrobblerTSVImportSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)


class LastFmImportViewSet(viewsets.ModelViewSet):
    queryset = LastFmImport.objects.all().order_by("-created")
    serializer_class = LastFmImportSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)
