#!./bin/python3

import os

import yaml
import pygame # type: ignore
from typing import Dict
import random
import tempfile
import handler
from handler import stream, m3u, dir

class Menu:
    '''
    Control object which holds the menu state.
    '''

    def __init__(self, config, display):
        self._display = display # Display object
        self._current_item = None # Current item with display control

        # Register default handlers

        self.handler = {
            "stream" : stream.StreamHandler(config, display),
            "m3u" : m3u.M3UHandler(config, display),
            "dir" : dir.DirectoryHandler(config, display)
        }

        # Playlist data

        playlistsFile = config.get("playlists", "music.yml")
        self.playlists = yaml.safe_load(open(playlistsFile)).get("playlist", [])
        self.playlists_pointer = 0

        self.update()

    def update(self):

        # Delegate to the current item if there is one

        if self._current_item is not None:
            self._current_item.update()
            return

        # Show the slice of the main menu which is relevant

        playlist_display = []

        maxlines = self._display.drawlines

        for i, item in enumerate(self.playlists):

            if len(playlist_display) <= maxlines:
                if i >= self.playlists_pointer - maxlines and i <= self.playlists_pointer + maxlines:
                    playlist_display.append(item.get("name", "<unknown>"))
            else:
                break

        playlist_pointer = self.playlists_pointer
        self._display.update(playlist_display, min(playlist_pointer, maxlines))

    def emitEvent(self, event):

        # Delegate to the current item if there is one

        if self._current_item is not None:
            try:
                self._current_item.emitEvent(event)
            except handler.HandlerExit as e:
                self._current_item = None

            self.update()

            return

        if event == handler.EVENT_RIGHT:
            self.selectPlaylistItem(self.playlists[self.playlists_pointer])

        if event == handler.EVENT_UP:
            self.playlists_pointer -=1

        if event == handler.EVENT_DOWN:
            self.playlists_pointer +=1

        if self.playlists_pointer >= len(self.playlists):
            self.playlists_pointer = 0

        if self.playlists_pointer < 0:
            self.playlists_pointer = len(self.playlists) - 1

        self.update()

    def selectPlaylistItem(self, item):
        handler = self.handler.get(item["type"])

        print("Selecting:", item)

        if handler is not None:
            handler.setPlaylistItem(item)
            self._current_item = handler
