# -*- coding: utf-8 -*-
"""Which row the hero of a cinematic Home section reads (docs/plan/skin-milionar/190-cinema.md, 220-hero-buttons.md).

The hero always shows the selected item of the current row: a card that is no title (a genre, a row action) has a hero
of its own (hero.tile), so the hero never shows something the cursor is not on. Only before any row was current, or when
the current row emptied, it shows the first row with a title. The skin used to work this out in generated conditions that compared every slot with every other one (2 MB of XML for 7 slots, 3 MB for 14). Now one
Window(Home) property names the row: milionar.hero.<sec> = its list id, and per slot the skin tests only that.

  * A row sets it itself when it gets the focus (gen_cinema ROW, no delay).
  * This watcher does the rest a few times a second: the first row with a title when nothing (or an emptied row) is
    named, and the borrowed buttons of an emptied current row: milionar.hero.<sec>.lent = true and .lent.<b1…> copied
    from the hero item's milionar.hero.s<slot>.* (written by hero_buttons.lent when the rows are built).
"""
import xbmc
import xbmcgui

from wcs.genres import contract as genre
from wcs.skin.hero_contract import BASES, SECTIONS, list_id, slot_count

# list base of every hero with rows: the sections and the genre page (a section's hero with its own buttons)
SOURCES = dict(BASES, **{genre.SEC: genre.BASE})

SOURCE = 'milionar.hero.{}'
LENT = 'milionar.hero.{}.lent'
LENT_FIELDS = ('b1', 'b2', 'b3', 'b4', 'b1l', 'b2l', 'b3l', 'b4l', 'b1i')
POLL = 1.0                       # the section on screen: a row's focus sets the source itself, this is for a row that emptied
IDLE = 2.0                       # Home not active / another skin
ALL_EVERY = 10                   # every 10th tick also the sections kept warm off-screen
# Home on screen with nothing modal over it. Under a modal dialog (the settings menu, the update window, a context menu)
# Container(<id>) of a Home list answers from the dialog, i.e. '' / no items: a tick then would take every row for empty
# and switch the hero off (Standa 2026-11-09, the update window). Until the dialog closes everything stays as it is.
SCREEN = 'Window.IsActive(home) + !System.HasActiveModalDialog'


def choose(current, rows):
    """The list id the hero reads. `current`: the current row's list id (''); `rows`: [(list id, has items, the selected
    item has a title)] in slot order. The current row when it has items, else the first row with a title, else ''."""
    for lid, items, _titled in rows:
        if lid == current and items:
            return lid
    return next((lid for lid, items, titled in rows if items and titled), '')


def lent_slot(current, source, rows_by_lid):
    """The slot whose button layout applies to the hero item: the current row when it is not the source (it emptied),
    else None. `rows_by_lid`: {list id: slot}."""
    if current and source and current != source and current in rows_by_lid:
        return rows_by_lid[current]
    return None


class Watcher(object):
    def __init__(self):
        self.home = xbmcgui.Window(10000)
        self.lent_key = {}

    def _rows(self, sec):
        rows = []
        for n in range(1, slot_count(sec) + 1):
            row = xbmc.getInfoLabel('Skin.String(mil.{}.{}.type)'.format(sec, n))
            if row and row != 'off':
                rows.append((n, str(list_id(SOURCES[sec], n))))
        return rows

    def _state(self, lid):
        items = xbmc.getCondVisibility('Integer.IsGreater(Container({}).NumItems,0)'.format(lid))
        return items, items and bool(xbmc.getInfoLabel('Container({}).ListItem.Property(milionar.hero.title)'.format(lid)))

    def tick(self, sec):
        current = self.home.getProperty('milionar.row.' + sec)
        source = self.home.getProperty(SOURCE.format(sec))
        if current and current == source and self._state(current)[0]:
            self._lend(sec, None, source)                    # the usual case: browsing a row
            return
        slots = self._rows(sec)
        if not slots:
            return
        chosen = choose(current, [(lid,) + tuple(self._state(lid)) for _n, lid in slots])
        if chosen != source:
            if chosen:
                self.home.setProperty(SOURCE.format(sec), chosen)
            else:
                self.home.clearProperty(SOURCE.format(sec))
        self._lend(sec, lent_slot(current, chosen, {lid: n for n, lid in slots}), chosen)

    def _lend(self, sec, slot, source):
        """Copy the borrowed buttons of row `slot` from the hero item (or clear them when no row borrows)."""
        key = (slot, source, xbmc.getInfoLabel('Container({}).CurrentItem'.format(source)) if slot else '')
        if self.lent_key.get(sec) == key:
            return
        self.lent_key[sec] = key
        item = 'Container({}).ListItem.Property(milionar.hero.s{}{})'.format
        if slot and xbmc.getInfoLabel(item(source, slot, '')):
            for field in LENT_FIELDS:
                self.home.setProperty('{}.{}'.format(LENT.format(sec), field), xbmc.getInfoLabel(item(source, slot, '.' + field)))
            self.home.setProperty(LENT.format(sec), 'true')
        else:
            self.home.clearProperty(LENT.format(sec))
            for field in LENT_FIELDS:
                self.home.clearProperty('{}.{}'.format(LENT.format(sec), field))


def _on_screen():
    """The hero on screen: the genre page when it is open in the section the menu shows, else that section's."""
    from wcs.skin import pages, warm
    if pages.here('milionar.detail.'):
        return None                                  # the detail's hero is pinned to its title
    if pages.here(genre.PREFIX):
        return genre.SEC
    sec = warm.BY_MENU.get(pages.menu_item())
    return sec if sec in SECTIONS else None


def run(monitor):
    from wcs.skin import family, paging
    watcher = Watcher()
    tick = 0
    while not monitor.abortRequested():
        if family.active() and xbmc.getCondVisibility(SCREEN):
            tick += 1
            focused = _on_screen()
            if focused is None:
                try:
                    from wcs.skin import detail
                    detail.tick()
                except Exception as exc:
                    xbmc.log('[Milionář Skin] pinned hero: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
            if focused:
                try:
                    paging.tick(focused)                     # a paged row grows near its end (wcs/skin/paging.py)
                except Exception as exc:
                    xbmc.log('[Milionář Skin] row paging {}: {}: {}'.format(focused, type(exc).__name__, exc), xbmc.LOGWARNING)
            for sec in dict.fromkeys(((focused,) if focused else ()) + (SECTIONS if tick % ALL_EVERY == 0 else ())):
                try:
                    watcher.tick(sec)
                except Exception as exc:                     # the hero must never stop the service
                    xbmc.log('[Milionář Skin] hero source {}: {}: {}'.format(sec, type(exc).__name__, exc), xbmc.LOGWARNING)
            wait = POLL
        else:
            wait = IDLE
        if monitor.waitForAbort(wait):
            return


def start(monitor):
    import threading
    threading.Thread(target=run, args=(monitor,), name='milionar-hero-source', daemon=True).start()
