import json

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 djangorestframework_camel_case.render import CamelCaseJSONRenderer

from owltail.ws_server import WebSocketMixin

from .player import player
from .const import STOP_SESSION
from .serializers import MusicSessionSerializer, WifiConnectionSerializer
from .wifi_handler import get_wifi_networks, connect


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, request.user.username)
        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)


class WifiNetworksAPI(APIView):
    def get(self, request, *args, **kwargs):
        return Response(data=get_wifi_networks(), status=status.HTTP_200_OK)


class WifiConnectAPI(APIView):
    def put(self, request, *args, **kwargs):
        serializer = WifiConnectionSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if connect(
            serializer.validated_data.get('ssid'),
            serializer.validated_data.get('password', None)
        ):
            return Response(status=status.HTTP_204_NO_CONTENT)
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ConfigurationAPI(APIView):
    renderer_classes = (CamelCaseJSONRenderer, )

    def get(self, request, *args, **kwargs):
        with open(settings.CONFIG_FILE_PATH, 'r') as config_file:
            json_conf = json.load(config_file)
            return Response(data=json_conf, status=status.HTTP_200_OK)
