# -*- coding: utf-8 -*-
"""Whether the first-run guide is due, and where it stands (docs/plan/onboarding/000-plan.md D4, D16, D27, D28).

Everyone who has not finished the guide gets it (D27), and without a TMDb key the addon never starts (D4). Signed in,
the account decides (D28): every web account counts as finished unless its own guide begun at registration is still
open; an account without a guide comes as an empty step. Nothing heavy here: the service asks at every start.
"""
import xbmcgui

STEP = 'onboarding_step'                 # setting: '' (never begun), the step the guide stands at, or DONE
DONE = 'done'
STEPS = ('welcome', 'account', 'tmdb', 'webshare', 'ai', 'genres', 'movies', 'series')
STORED = ('welcome', 'tmdb', 'webshare', 'ai', 'genres', 'movies', 'series')   # the web's steps: 'account' never stored
PROPERTY = 'milionar.onboarding'         # Window(Home): the guide is due; the skin covers Home with its own screen
FINISHED = 'milionar.onboarding.finished'  # Window(Home): the guide just ended; the service starts everything else
FRESH = 'milionar.onboarding.fresh'      # Window(Home): a new install (only it gets all the skin's defaults)


def _addon():
    """Read fresh: another process (the settings, a key window, a pull of the account) may have just written it."""
    import xbmcaddon
    return xbmcaddon.Addon('plugin.video.milionar')


def has_key(addon=None):
    return bool(_addon().getSetting('tmdb_api_key'))


def _signed_in():
    from wcs.account import state as account_state
    account_state.invalidate()
    return account_state.signed_in()


def finished(addon=None):
    """The guide is done: on this device, or (signed in) an account without a guide of its own (D28)."""
    current = _addon().getSetting(STEP)
    return current == DONE or (current == '' and _signed_in())


def pending(addon=None):
    return not has_key() or not finished()


def step(addon=None):
    """The step the guide opens at: Vítej without a key (D4) or when it never began, else the stored one (D16)."""
    current = _addon().getSetting(STEP)
    if not has_key() or current not in STORED:
        return STEPS[0]
    return current


def remember(addon, name):
    if name in STORED or name == DONE:
        addon.setSetting(STEP, name)


def cover(on):
    """The skin's own screen over Home while the guide is due (Home.xml), so no empty Home shows between skin loads."""
    home = xbmcgui.Window(10000)
    if on:
        home.setProperty(PROPERTY, '1')
    else:
        home.clearProperty(PROPERTY)
        home.clearProperty(FRESH)


def covered():
    return bool(xbmcgui.Window(10000).getProperty(PROPERTY))


def mark_fresh():
    """Before the cover: this is a new install (no key, the guide never began), not an existing user (D27)."""
    if not has_key() and _addon().getSetting(STEP) == '':
        xbmcgui.Window(10000).setProperty(FRESH, '1')


def fresh():
    return bool(xbmcgui.Window(10000).getProperty(FRESH))
