# -*- coding: utf-8 -*-
"""The widget-style menu editor; item menus use Kodi's native context dialog."""
import copy

import xbmcaddon
import xbmcgui

from wcs.skin import context

BACK = (10, 92, 216)


class Menu:
    """What the editor edits: the context menu of a widget."""
    header, column, to_main, to_more = 32600, 32628, 32606, 32607
    groups = {'main': 32602, 'more': 32420, 'hidden': 32603}
    normalize, defaults = staticmethod(context.normalize), staticmethod(context.defaults)

    @staticmethod
    def settle(config):
        return False


class Hero(Menu):
    """The hero buttons of a widget (wcs/skin/hero_buttons.py): the same editor, other names, at most four buttons."""
    from wcs.skin import hero_buttons
    header, column, to_main, to_more = hero_buttons.S_TITLE, hero_buttons.S_COLUMN, hero_buttons.S_TO_MAIN, hero_buttons.S_TO_MORE
    groups = {'main': hero_buttons.S_TITLE, 'more': hero_buttons.S_MORE, 'hidden': 32603}
    normalize, defaults = staticmethod(hero_buttons.normalize), staticmethod(hero_buttons.defaults)

    @staticmethod
    def settle(config):
        """Move what does not fit to More options; True when something moved (the editor says so)."""
        from wcs.skin import hero_buttons
        return hero_buttons.limit(config)


class MenuManager(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        self.row = kwargs.pop('row')
        self.title = kwargs.pop('title', '')
        self.model = kwargs.pop('model', Menu)
        self.config = self.model.normalize(self.row, copy.deepcopy(kwargs.pop('config')))
        super().__init__(*args, **kwargs)
        self.original = copy.deepcopy(self.config)
        self.result = None

    def onInit(self):
        from wcs.skin.slots import TITLES
        self.setProperty('ctx.header', self.title or (context.text(self.model.header) + ': ' + context.text(TITLES[self.row])))
        for name in ('column', 'to_main', 'to_more'):
            self.setProperty('ctx.' + name, context.text(getattr(self.model, name)))
        self._fill()
        self.setFocusId(9000)

    def _fill(self, selected=None):
        self.entries = [(group, action) for group in ('main', 'more', 'hidden') for action in self.config[group]]
        labels = self.model.groups
        items = []
        for number, (group, action) in enumerate(self.entries, 1):
            item = xbmcgui.ListItem(context.label(self.row, action), context.text(labels[group]))
            item.setProperty('num', str(number))
            items.append(item)
        control = self.getControl(9000)
        control.reset()
        control.addItems(items)
        if selected:
            control.selectItem(next((i for i, entry in enumerate(self.entries) if entry[1] == selected), 0))

    def _cancel(self):
        if self.config == self.original or xbmcgui.Dialog().yesno('Milionář', context.text(32370)):
            self.close()

    def onAction(self, action):
        if action.getId() in BACK:
            self._cancel()

    def onClick(self, control_id):
        if control_id == 9108:
            self.result = copy.deepcopy(self.config)
            self.close()
            return
        if control_id == 9109:
            self._cancel()
            return
        if control_id == 9107:
            self.config = self.model.defaults(self.row)
            self._fill()
            return
        i = self.getControl(9000).getSelectedPosition()
        if not 0 <= i < len(self.entries):
            return
        group, action = self.entries[i]
        values = self.config[group]
        position = values.index(action)
        if control_id in (9101, 9102):
            target = position + (-1 if control_id == 9101 else 1)
            if 0 <= target < len(values):
                values[position], values[target] = values[target], values[position]
        elif control_id in (9103, 9104, 9105):
            target = {9103: 'main', 9104: 'more', 9105: 'hidden'}[control_id]
            if target != group:
                values.remove(action)
                self.config[target].append(action)
                if self.model.settle(self.config):
                    from wcs.skin import hero_buttons
                    xbmcgui.Dialog().notification('Milionář', context.text(hero_buttons.S_LIMIT).format(hero_buttons.LIMIT))
        self._fill(action)


def edit_hero(row, config):
    return edit(row, config, Hero)


def edit(row, config, model=Menu, title=''):
    dialog = MenuManager('skin/DialogMilionarContextManager.xml', xbmcaddon.Addon().getAddonInfo('path'),
                         'Default', '1080i', row=row, config=config, model=model, title=title)
    dialog.doModal()
    result = dialog.result
    del dialog
    return result
