# -*- coding: utf-8 -*-
"""Rows that grow by STEP cards when the cursor nears their end (Standa 2026-11-09: Všechny moje seriály / filmy).

A Home row is a file Kodi reads itself (rowfiles.py), so it cannot ask for more cards. The service's hero watcher
(hero_source.run) already looks at the focused row of the section on screen once a second; for a paged row it also
calls tick(): when the cursor is within AHEAD cards of the end of a full row, the row's Home property
milionar.rowmore.<sec>.<slot> grows by STEP and the row is built again with that many more cards (journal.request_params
reads it). A reloaded list keeps its focus by the cards' paths, so the cursor stays where it is.

Cost on a weak TV: nothing new runs. Outside a paged row a tick is one property read and one cached comparison; on a
paged row three info labels; a build only when the end comes near, and never twice for the same size.
"""
import xbmc
import xbmcgui

PAGED = ('my_series_all', 'my_movies_all')
STEP = 10
AHEAD = 3                                # cards before the end that start the next page
CAP = 99                                 # the skin's lists show at most rowfiles.MANY cards (known_items tests 99)
MORE = 'milionar.rowmore.{}.{}'          # Home property: the cards a paged row shows on top of its own limit
ROW = 'milionar.row.{}'                  # Home property: the list id of the section's focused row (gen_cinema)

_home = None
_slots = {}                              # (sec, list id) -> (slot, row type): the focused row's slot, cached per type
_asked = {}                              # (sec, slot) -> the size already asked for


def more(sec, slot, home=None):
    """The extra cards of row (sec, slot): 0 for a row that never grew."""
    try:
        return max(0, int((home or _window()).getProperty(MORE.format(sec, slot)) or 0))
    except ValueError:
        return 0


def _window():
    global _home
    if _home is None:
        _home = xbmcgui.Window(10000)
    return _home


def _slot_of(sec, lid):
    """(slot, row type) of the section's row with list id `lid`, or (None, '')."""
    from wcs.skin.hero_contract import BASES, list_id, slot_count
    if sec not in BASES:
        return None, ''
    for n in range(1, slot_count(sec) + 1):
        if str(list_id(BASES[sec], n)) == lid:
            return n, xbmc.getInfoLabel('Skin.String(mil.{}.{}.type)'.format(sec, n))
    return None, ''


def _int(label):
    try:
        return int(xbmc.getInfoLabel(label) or 0)
    except ValueError:
        return 0


def tick(sec):
    """One look at the focused row of section `sec` (hero watcher thread)."""
    home = _window()
    lid = home.getProperty(ROW.format(sec))
    if not lid:
        return
    cached = _slots.get((sec, lid))
    if cached is None or (cached[0] is not None
                          and xbmc.getInfoLabel('Skin.String(mil.{}.{}.type)'.format(sec, cached[0])) != cached[1]):
        cached = _slots[(sec, lid)] = _slot_of(sec, lid)
    slot, row = cached
    if slot is None or row not in PAGED:
        return
    if xbmc.getCondVisibility('Container({}).IsUpdating'.format(lid)):
        return
    count = _int('Container({}).NumItems'.format(lid))
    position = _int('Container({}).CurrentItem'.format(lid))
    if not count or position < count - AHEAD or count >= CAP:
        return
    extra = more(sec, slot, home)
    if count < _limit(sec, slot) + extra:
        return                                       # the row holds every card there is
    size = count + STEP
    if _asked.get((sec, slot)) == size:
        return
    _asked[(sec, slot)] = size
    home.setProperty(MORE.format(sec, slot), str(extra + STEP))
    from wcs.skin import journal
    journal.request([(sec, slot)])
    xbmc.log('[Milionář Skin] row {}.{} {} grows to {} cards'.format(sec, slot, row, size), xbmc.LOGINFO)


def _limit(sec, slot):
    """The row's own card count, as the build caps it (journal.normalize, performance.limit)."""
    from wcs.skin import journal
    try:
        value = int(xbmc.getInfoLabel('Skin.String(mil.{}.{}.limit)'.format(sec, slot)) or journal.MAX_ITEMS)
    except ValueError:
        value = journal.MAX_ITEMS
    value = min(value, journal.MAX_ITEMS)
    try:
        from wcs.skin.performance import limit
        return limit(value)
    except ImportError:
        return value
