from os import listdir

from django.conf import settings
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from owltail.ws_server import WebSocketMixin

from .player import player
from .const import STOP_SESSION
from .serializers import MusicSessionSerializer


class MusicSession(WebSocketMixin, APIView):
    serializer_class = MusicSessionSerializer

    def put(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        source = serializer.validated_data['source']
        duration = serializer.validated_data['duration']
        player.playlist_start(source, duration * 60)
        return Response(data=serializer.data, status=status.HTTP_200_OK)

    def delete(self, request, *args, **kwargs):
        player.playlist_stop()
        self._send_ws_message_close({'operationId': STOP_SESSION})
        return Response(status=status.HTTP_204_NO_CONTENT)


class PlaylistsAPI(APIView):
    def get(self, request, *args, **kwargs):
        folders = listdir(settings.DEFAULT_SONGS_FOLDER)
        return Response(data=folders, status=status.HTTP_200_OK)
