# -*- coding: utf-8 -*-
"""The service's sync threads (docs/plan/milionar-account/020 §5). Started only on a signed-in device.

milionar-sync-push: the documents round every 10 s (and at once after a local change), then the outbox.
milionar-sync-pull: long-polls the server (wait 20 s with a heartbeat, so Kodi's stop ends it within ~2 s, T4).
milionar-remote-game: long-polls the game ChatGPT opened and opens its card (wcs/games/remote, WEB docs/plan/kodi-game).
Both step aside for the user (wcs/skin/userfirst.py), never touch GUI controls and end with Kodi's abort."""
import threading
import time

from wcs.account import client, hooks, state

DOCS_EVERY = 10.0
SETTINGS_CHANGED = 'milionar.account.settings'     # Window(Home) property bumped by the service on onSettingsChanged
WAIT_S = 20
_threads = []
_stop = threading.Event()


def _log(message):
    client._log(message)


def _home():
    import xbmcgui
    return xbmcgui.Window(10000)


def publish_label():
    """The account item of the skin's settings menu (S24): "Účet: <jméno>" / "Přihlásit účet"."""
    try:
        import xbmcaddon
        addon = xbmcaddon.Addon(state.ADDON_ID)
        name = addon.getSetting(state.NAME) if state.signed_in() else ''
        label = addon.getLocalizedString(36000).format(name) if name else addon.getLocalizedString(36001)
        _home().setProperty(state.HOME_LABEL, label)
        status = (addon.getLocalizedString(36029).format(name, addon.getSetting(state.EMAIL)) if name
                  else addon.getLocalizedString(36028))
        if addon.getSetting('account_status') != status:
            addon.setSetting('account_status', status)
    except Exception:
        pass


def _push_loop(monitor):
    from wcs.account import docs, sync
    from wcs.skin import userfirst
    userfirst.background_thread()
    last_docs, last_wake, failures = 0.0, None, 0
    last_settings = None
    while not monitor.abortRequested() and not _stop.is_set():
        if userfirst.give_way(monitor):
            return
        try:
            wake = _home().getProperty(hooks.WAKE)
            now = time.monotonic()
            settings_mark = _home().getProperty(SETTINGS_CHANGED)
            if now - last_docs >= DOCS_EVERY or wake != last_wake or settings_mark != last_settings:
                # the account settings are read only after Kodi said they changed (first round: always)
                sync.queue_docs(dialog_open=sync._dialog_open(), settings=settings_mark != last_settings)
                last_settings = settings_mark
                docs.apply_pending_settings()
                last_docs, last_wake = now, wake
            while sync.push_once() and not monitor.abortRequested():
                pass
            failures = 0
        except client.AccountError as exc:
            if exc.code == 'unauthorized':
                _remote_signout(monitor, push=False)
                return
            failures += 1
            if failures in (1, 10):
                _log('push waits: {}'.format(exc.code))
        except Exception as exc:
            failures += 1                         # an unexpected error backs off too (no log every half second)
            if failures in (1, 10) or failures % 100 == 0:
                _log('push failed: {}: {}'.format(type(exc).__name__, exc))
        if monitor.waitForAbort(0.5 if not failures else min(30, 2 ** min(failures, 5))):
            return


def _pull_loop(monitor):
    from wcs.account import sync
    from wcs.skin import userfirst
    userfirst.background_thread()
    failures = 0
    while not monitor.abortRequested() and not _stop.is_set():
        if userfirst.give_way(monitor):
            return
        try:
            result = sync.pull_once(WAIT_S, lambda: monitor.abortRequested() or _stop.is_set())
            failures = 0
            if result == 'logout':
                _remote_signout(monitor, push=True)
                return
            if result == 'changes':
                continue
        except client.AccountError as exc:
            if exc.code == 'aborted':
                return
            if exc.code == 'unauthorized':
                _remote_signout(monitor, push=False)
                return
            failures += 1
            if failures in (1, 10):
                _log('pull waits: {}'.format(exc.code))
            if monitor.waitForAbort(min(60, 2 ** min(failures, 6))):
                return
        except Exception as exc:
            failures += 1
            if failures in (1, 10) or failures % 100 == 0:
                _log('pull failed: {}: {}'.format(type(exc).__name__, exc))
            if monitor.waitForAbort(min(60, 5 * failures)):
                return


def _game_loop(monitor):
    from wcs.games.remote import listener
    listener.loop(monitor, _stop.is_set)


def _playback_loop(monitor):
    from wcs.playback.remote import listener
    listener.loop(monitor, _stop.is_set)


def _remote_signout(monitor, push):
    """T13: the web signed this device out (or the account is gone): finish it safely in its own thread."""
    from wcs.account import switch
    _stop.set()

    def signout():
        switch.remote_signout(monitor, push)
        from wcs.account import service
        service.guide_when_due(monitor, wait=False)      # onboarding D32
    threading.Thread(target=signout, name='milionar-account-signout', daemon=True).start()


def start(monitor):
    """Service start (and after a sign-in): the threads, once."""
    publish_label()
    if not state.signed_in() or any(t.is_alive() for t in _threads):
        return
    _stop.clear()
    del _threads[:]
    for name, target in (('milionar-sync-push', _push_loop), ('milionar-sync-pull', _pull_loop),
                         ('milionar-remote-game', _game_loop), ('milionar-remote-playback', _playback_loop)):
        thread = threading.Thread(target=target, args=(monitor,), name=name, daemon=True)
        thread.start()
        _threads.append(thread)


def stop(timeout=3.0):
    """Before a switch: the threads end (the pull ends within ~2 s, the push after its request)."""
    _stop.set()
    deadline = time.monotonic() + timeout
    for thread in list(_threads):
        thread.join(max(0.0, deadline - time.monotonic()))
    return not any(t.is_alive() for t in _threads)
