#!./bin/python3

import os

from handler import BaseHandler, EVENT_UP, EVENT_RIGHT, EVENT_DOWN
from handler.lib.pymplb import MPlayer

class BaseListHandler(BaseHandler):

    def __init__(self, config, display):
        super().__init__(config, display)
        self.items = []


    def setItems(self, items):
        '''
        Set the items which should be displayed.
        '''
        self.items = items
        self.item_pointer = 0


    def update(self, text=None, highlight=-1, title=None, img=None):
        '''
        Called when the handler should update the display.
        '''

        # Show the slice of the main menu which is relevant

        playlist_display = text or []

        maxlines = self.display.drawlines

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

        super().update(playlist_display,
            highlight if highlight != -1 else min(self.item_pointer, maxlines),
            title, img)


    def emitEvent(self, event):
        '''
        Called when an event has happened.
        '''
        super().emitEvent(event)

        if event == EVENT_RIGHT:
            item = self.items[self.item_pointer]
            self.itemSelected(item)

        if event == EVENT_UP:
            self.item_pointer -=1

        if event == EVENT_DOWN:
            self.item_pointer +=1

        if self.item_pointer >= len(self.items):
            self.item_pointer = 0

        if self.item_pointer < 0:
            self.item_pointer = len(self.items) - 1


    def nextItem(self):
        self.item_pointer +=1
        if self.item_pointer >= len(self.items):
            self.item_pointer = 0
        item = self.items[self.item_pointer]
        self.itemSelected(item)
        self.update()


    def itemSelected(self, item):
        '''
        Called when an item has been selected by the user.
        '''
        pass
