from django_filters import rest_framework as filters
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from .models import Sound, Track
from .serializers import SoundSerializer, admin
from .views import BaseAPIView

__all__ = (
    "SoundFilter",
    "SoundViewSet",
    "TrackFilter",
    "TrackROViewSet",
    "UserSettingsViewSet",
)


class SoundFilter(filters.FilterSet):
    station = filters.NumberFilter(field_name="program__station__id")
    program = filters.NumberFilter(field_name="program_id")
    episode = filters.NumberFilter(field_name="episode_id")
    search = filters.CharFilter(field_name="search", method="search_filter")

    def search_filter(self, queryset, name, value):
        return queryset.search(value)


class SoundViewSet(BaseAPIView, viewsets.ModelViewSet):
    serializer_class = SoundSerializer
    queryset = Sound.objects.available().order_by("-pk")
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = SoundFilter


# --- admin
class TrackFilter(filters.FilterSet):
    artist = filters.CharFilter(field_name="artist", lookup_expr="icontains")
    album = filters.CharFilter(field_name="album", lookup_expr="icontains")
    title = filters.CharFilter(field_name="title", lookup_expr="icontains")


class TrackROViewSet(viewsets.ReadOnlyModelViewSet):
    """Track viewset used for auto completion."""

    serializer_class = admin.TrackSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = TrackFilter
    queryset = Track.objects.all()

    @action(name="autocomplete", detail=False)
    def autocomplete(self, request):
        field = request.GET.get("field", None)
        if field:
            queryset = self.filter_queryset(self.get_queryset())
            values = queryset.values_list(field, flat=True).distinct()
            return Response(values)
        return self.list(request)


class UserSettingsViewSet(viewsets.ViewSet):
    """User's settings specific to aircox.

    Allow only to create and edit user's own settings.
    """

    serializer_class = admin.UserSettingsSerializer
    permission_classes = [IsAuthenticated]

    def get_serializer(self, instance=None, **kwargs):
        return self.serializer_class(instance=instance, context={"user": self.request.user}, **kwargs)

    @action(detail=False, methods=["GET"])
    def retrieve(self, request):
        user = self.request.user
        settings = getattr(user, "aircox_settings", None)
        data = settings and self.get_serializer(settings) or None
        return Response(data)

    @action(detail=False, methods=["POST", "PUT"])
    def update(self, request):
        user = self.request.user
        settings = getattr(user, "aircox_settings", None)
        data = dict(request.data)
        data["user_id"] = self.request.user
        serializer = self.get_serializer(instance=settings, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"status": "ok"})
        else:
            return Response(
                {"errors": serializer.errors},
                status=status.HTTP_400_BAD_REQUEST,
            )
