# -*- coding: utf-8 -*-
"""Start the first-run guide, from the service at Kodi's start or from the addon opened while it is due.

Every skin load closes all windows, so the guide opens only once the skin is in place: our skin, all its defaults and
its palette, one setup that the skin covers with its own screen (Home.xml, state.cover). Until the guide ends, the
service starts nothing else: no rows, no Pro tebe, no TMDb call (D4, D19). While Kodi runs, the guide also opens
whenever it becomes due (when_due: a sign-out, a sign-in from the menu to an account with an open guide, D32).
"""
import xbmc
import xbmcaddon
import xbmcgui

from wcs.onboarding import state

ADDON_ID = 'plugin.video.milionar'
OPEN = 'milionar.onboarding.open'        # Window(Home): the guide window is up (one guide at a time)
GUIDE = 'RunPlugin(plugin://plugin.video.milionar/?action=onboarding)'


def _log(message, level=xbmc.LOGINFO):
    xbmc.log('[Milionář Onboarding] ' + message, level)


def prepare_skin():
    """Our skin with its defaults and palette (wcs/skin/transition.py, defaults.first_setup); True when it is active."""
    from wcs.skin import installer, transition
    addon = xbmcaddon.Addon(ADDON_ID)
    if xbmc.getSkinDir() != installer.SKIN_ID:
        addon.setSetting(transition.COMPLETED, '')        # back to Estuary (D5): the switch runs again
    if not transition.run():
        return False
    if xbmc.getSkinDir() != installer.SKIN_ID:
        return False
    # The switch happened before (transition done): what the Home <onload> chain could not write under the cover now,
    # loaded once more before the guide opens (it waits for the last skin load, _settled). Nothing when all is there.
    from wcs.skin import defaults
    if state.covered() and defaults.first_setup():
        xbmc.executebuiltin('ReloadSkin()', True)
    return True


def _settled(monitor, seconds=0.6):
    """The skin's last load is over: Home is up without a dialog for a moment."""
    quiet = lambda: (xbmc.getCondVisibility('Window.IsActive(home)') and
                     not xbmc.getCondVisibility('System.HasActiveModalDialog'))
    for _ in range(300):                               # at most about 30 s
        if quiet():
            if monitor.waitForAbort(seconds):
                return False
            if quiet():
                return True
        elif monitor.waitForAbort(0.1):
            return False
    return True


def open_guide():
    if not xbmcgui.Window(10000).getProperty(OPEN):
        xbmc.executebuiltin(GUIDE)


def coordinate(monitor, start_rest):
    """Service, while the guide is due: skin, guide, and everything else once the guide has ended."""
    home = xbmcgui.Window(10000)
    state.mark_fresh()
    state.cover(True)
    while home.getProperty('milionar.skin.installing'):     # the skin's files (service.start_skin_installer)
        if monitor.waitForAbort(0.2):
            return
    for attempt in range(5):
        if prepare_skin():
            break
        _log('skin setup deferred ({})'.format(attempt + 1), xbmc.LOGWARNING)
        if monitor.waitForAbort(2):
            return
    if not _settled(monitor):
        return
    open_guide()
    while not home.getProperty(state.FINISHED):
        if monitor.waitForAbort(0.3):
            return
    home.clearProperty(state.FINISHED)
    _log('guide finished: the service starts')
    start_rest()             # Pro tebe of the guide stays until its usual rebuild (D26; a refinement took 219 s on the TV)
    account_home()


def account_home():
    """Signed in during the guide: its cover hid Kodi's bar of the account (wcs/account/progress.py), and Home still
    fills (titles' data, Pro tebe of the account). The bar shows now and lasts until nothing comes any more."""
    try:
        from wcs.account import progress, state as account_state
        account_state.invalidate()
        if account_state.signed_in():
            progress.begin_signin()
    except Exception as exc:
        _log('account progress after the guide: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)


def from_addon():
    """The addon opened while the guide is due: the same setup, then the guide in this process."""
    state.mark_fresh()
    state.cover(True)
    if not prepare_skin():
        state.cover(False)
        xbmcgui.Dialog().notification('Milionář', xbmcaddon.Addon(ADDON_ID).getLocalizedString(35808),
                                      xbmcgui.NOTIFICATION_ERROR, 5000)
        return
    _settled(xbmc.Monitor())
    from wcs.onboarding import wizard
    wizard.run()


def when_due(monitor):
    """Service, while Kodi runs (D32): the guide now if it has become due (a sign-out left this device without a finished
    guide, a sign-in from the menu brought an account whose guide is open). Home stays covered until it ends; the rows
    keep running underneath. Only in our skin: otherwise the next start of the addon sets it up (from_addon)."""
    from wcs.account import ui as account_ui
    from wcs.skin import installer
    home = xbmcgui.Window(10000)
    while home.getProperty(account_ui.OPEN):            # the account window (its merge offer) is answered first
        if monitor.waitForAbort(0.3):
            return
    if home.getProperty(OPEN) or not state.pending() or xbmc.getSkinDir() != installer.SKIN_ID:
        return
    _log('the guide is due: opening it')
    state.cover(True)
    home.clearProperty(state.FINISHED)
    open_guide()
    for _ in range(100):                                 # the plugin process starts the window
        if home.getProperty(OPEN) or monitor.waitForAbort(0.1):
            break
    while home.getProperty(OPEN):
        if monitor.waitForAbort(0.3):
            return
    if home.getProperty(state.FINISHED):
        home.clearProperty(state.FINISHED)
        _log('guide finished')
        account_home()
    else:
        state.cover(False)                               # closed without finishing (Původní vzhled cleared it already)
