# -*- coding: utf-8 -*-
"""Kodi's background progress while the account fills this device (Standa, 2026-11-07): after a sign-in and after a
pulled page of many changes, until the Home rows with the new content are built again (wcs/skin/journal.py). Never a
modal window, never during playback; the user keeps browsing. Service process only.

begin_signin(): the sign-in finished in the plugin, the rows follow. begin_changes(n) ... release(): a large page is
being applied. rows(done, total): the journal built a row. A watcher closes the dialog once nothing is held, the journal
is idle and nothing is asked of it."""
import threading
import time

import xbmc

LARGE = 50                    # a pulled page of this many changes shows the progress (the live sync stays silent)
S_HEADING, S_CHANGES, S_ROWS, S_PREPARING, S_MERGING, S_TITLES = 36002, 36035, 36036, 36037, 36042, 36060
IDLE_S = 2.0                  # the journal idle this long: the rows are done
LIMIT_S = 600.0               # never longer than this

_lock = threading.RLock()
_dialog = None
_held = 0
_started = 0.0
_rows = [0, 0]
_titles_seen = [0]                # the most titles waited for at once in this bar (its 100 %)
_merging = threading.Event()      # the merge owns the message until its ops are sent


def _text(string_id, *args):
    import xbmcaddon
    text = xbmcaddon.Addon('plugin.video.milionar').getLocalizedString(string_id)
    return text.format(*args) if args else text


def active():
    return _dialog is not None


def _guide_covers():
    """The first-run guide covers Home: its rows build unseen, and the bar would lie over the guide's step progress."""
    from wcs.onboarding import state
    return state.covered()


def _open(percent, message):
    global _dialog, _started
    import xbmcgui
    with _lock:
        if xbmc.getCondVisibility('Player.HasMedia'):
            return False
        if _dialog is None:
            _dialog = xbmcgui.DialogProgressBG()
            _dialog.create(_text(S_HEADING), message)
            _started = time.monotonic()
            _rows[:] = [0, 0]
            threading.Thread(target=_watch, name='milionar-account-progress', daemon=True).start()
        _dialog.update(int(percent), _text(S_HEADING), message)
        return True


def begin_signin():
    """The device now shows the account: its rows are being built (unseen under the first-run guide: no bar there)."""
    if not _guide_covers():
        _open(5, _text(S_PREPARING))


def begin_changes(count):
    """A page of `count` changes is applied now; release() when it is in."""
    global _held
    if count < LARGE:
        return False
    with _lock:
        if _merging.is_set() and _dialog is not None:  # the merge's own answers come back: its message stays
            _held += 1
            return True
        if _open(5, _text(S_CHANGES, count)):
            _held += 1
            return True
    return False


def begin_merge(pending=None):
    """The merge of this Kodi's data was queued (S28): "Slučuji: x z y" while its ops leave the outbox, then the rows."""
    global _held
    from wcs.account import merge
    count = pending or merge.pending
    total = count()
    if total <= 0:
        return False
    with _lock:
        if not _open(5, _text(S_MERGING, 0, total)):
            return False
        _held += 1
        _merging.set()
    threading.Thread(target=_merge_watch, args=(total, count), name='milionar-account-merge', daemon=True).start()
    return True


def _merge_watch(total, count):
    monitor = xbmc.Monitor()
    try:
        while not monitor.waitForAbort(1.0):
            with _lock:
                if _dialog is None:
                    return
            left = count()
            done = max(0, total - left)
            with _lock:
                if _dialog is not None:
                    _dialog.update(int(5 + 85 * done // total), _text(S_HEADING), _text(S_MERGING, done, total))
            if left <= 0:
                return
    finally:
        _merging.clear()
        release()


def release():
    global _held
    with _lock:
        _held = max(0, _held - 1)


def rows(done, total):
    """The journal built `done` of `total` rows of its current sweep."""
    with _lock:
        if _dialog is None or total <= 0 or _merging.is_set():
            return
        _rows[:] = [done, total]
        percent = 10 + 90 * min(done, total) // total
        _dialog.update(int(percent), _text(S_HEADING), _text(S_ROWS, min(done, total), total))


def finish():
    global _dialog, _held
    with _lock:
        dialog, _dialog, _held = _dialog, None, 0
    if dialog is not None:
        try:
            dialog.update(100)
            dialog.close()
        except Exception:
            pass


def waiting():
    """(Home still fills by itself, titles whose data are on the way). Not only the rows being built: after a sign-in
    the rows show what is cached and ask the service for the rest (wcs/skin/service.py), cards then appear one title at
    a time (Pokračovat of Pro tebe), and Pro tebe of the account is built, maybe in the plugin (foryou.lock)."""
    from wcs.foryou import service as foryou_service
    from wcs.skin import journal, service as skin_service
    titles = skin_service.titles_left()
    return journal.busy() or skin_service.loading() or foryou_service.building(), titles


def _titles(left):
    """Kodi's bar while only titles' data are still coming: how many are left (the rows' builds report themselves)."""
    from wcs.skin import journal
    with _lock:
        if _dialog is None or _merging.is_set() or journal.busy():
            return
        _titles_seen[0] = max(_titles_seen[0], left)
        total = _titles_seen[0]
        _dialog.update(int(10 + 85 * (total - left) // total), _text(S_HEADING), _text(S_TITLES, left))


def _watch():
    monitor = xbmc.Monitor()
    idle = 0.0
    _titles_seen[0] = 0
    while not monitor.waitForAbort(0.5):
        with _lock:
            if _dialog is None:
                return
            held = _held
            started = _started
        if xbmc.getCondVisibility('Player.HasMedia') or time.monotonic() - started > LIMIT_S:
            break
        if _guide_covers():                       # a sign-out opened the guide: the account's rows are no longer news
            break
        busy, titles = waiting()
        if titles:
            _titles(titles)
        idle = idle + 0.5 if not held and not busy else 0.0
        if idle >= IDLE_S:
            break
    finish()
