# -*- coding: utf-8 -*-
"""What Pro tebe shows: everything, films or series (docs/plan/pro-tebe/030).

The hero button "Zobrazit: Vše ▼" (action `fy_mode`, laid out by the hero button manager like every other button) and
the same entry of a card's context menu open the context menu with the three choices; the button's label names the
current one. The rows read the mode from Skin.String(mil.foryou.mode) (gen_slots.CONTENT), so a choice reloads them;
until they are back the section dims its rows under a spinner (Home property milionar.switching.foryou, gen_cinema).
"""
import xbmc
import xbmcaddon
import xbmcgui

ADDON_ID = 'plugin.video.milionar'
SEC = 'foryou'
ACTION = 'fy_mode'
SKIN_STRING = 'mil.{}.mode'.format(SEC)
SWITCHING = 'milionar.switching.{}'.format(SEC)
MODES = (('', 593), ('movie', 342), ('tv', 20343))      # value, Kodi's string: Vše, Filmy, Seriály
S_SHOW = 35344                                          # "Zobrazit: {}"
ARROW = ' [COLOR C0FFFFFF]▼[/COLOR]'                # the button opens a menu
START_WAIT_S, LOAD_WAIT_S, POLL_S = 2.0, 20.0, 0.2


def current():
    value = xbmc.getInfoLabel('Skin.String({})'.format(SKIN_STRING))
    return value if value in ('movie', 'tv') else ''


def name(mode):
    return xbmc.getLocalizedString(dict(MODES).get(mode or '', 593))


def label(mode=None):
    """The button's label: the current choice and the sign that it opens a menu."""
    text = xbmcaddon.Addon(ADDON_ID).getLocalizedString(S_SHOW) or 'Zobrazit: {}'
    return text.format(name(current() if mode is None else mode)) + ARROW


def builtin():
    return 'RunPlugin(plugin://{}/?action=foryou_mode)'.format(ADDON_ID)


def register(items, mode):
    """Give every item of a Pro tebe row the button (the hero shows it where the manager put it)."""
    from wcs.skin import hero
    text = label(mode if mode in ('movie', 'tv') else '')
    for entry in items:
        hero.direct(entry[1], ACTION, text, builtin())


def _rows():
    from wcs.skin.hero_contract import BASES, WIDGET_SLOTS
    return ['Container({}).IsUpdating'.format(BASES[SEC] + n * 100) for n in range(1, WIDGET_SLOTS + 1)]


def _updating():
    return any(xbmc.getCondVisibility(condition) for condition in _rows())


def _wait_for_rows(monitor):
    """The rows start loading a moment after the skin string changes: wait for that start, then for the end."""
    waited, started = 0.0, False
    while waited < START_WAIT_S + LOAD_WAIT_S:
        if monitor.waitForAbort(POLL_S):
            return
        waited += POLL_S
        if _updating():
            started = True
        elif started or waited >= START_WAIT_S:
            return


def set_mode(value):
    """Show `value` ('' all, movie, tv): the rows reload, the section shows it until they are back."""
    if value == current():
        return
    home = xbmcgui.Window(10000)
    home.setProperty(SWITCHING, '1')
    try:
        xbmc.executebuiltin('Skin.SetString({},{})'.format(SKIN_STRING, value) if value else
                            'Skin.Reset({})'.format(SKIN_STRING))
        _wait_for_rows(xbmc.Monitor())
    finally:
        home.clearProperty(SWITCHING)


def choose(params=None):
    """The context menu of the button: the three choices, then Další… with the editor of the hero buttons."""
    from wcs.skin import context, hero_buttons
    identity = (params or {}).get('ctx') or hero_buttons.focused_widget(xbmc.getInfoLabel('System.CurrentControlID'))
    top = [(name(value), value) for value, _string in MODES]
    more = [(context.text(hero_buttons.S_EDIT), context.builtin({'action': 'skin_hero', 'do': 'edit', 'ctx': identity}))] \
        if identity else []
    labels = [text for text, _value in top] + ([context.text(32420)] if more else [])
    from wcs.skin.menu_anchor import anchored
    home = xbmcgui.Window(10000)
    home.setProperty('milionar.ctx.active', '1')
    chosen = command = None
    try:
        with anchored():                                # where the menus of the cards open (over the buttons)
            index = xbmcgui.Dialog().contextmenu(labels)
            if 0 <= index < len(top):
                chosen = top[index][1]
            elif index >= len(top):
                sub = xbmcgui.Dialog().contextmenu([text for text, _command in more])
                command = more[sub][1] if sub >= 0 else None
    finally:
        home.clearProperty('milionar.ctx.active')
    if command:
        xbmc.executebuiltin(command)
    elif chosen is not None:
        set_mode(chosen)
