# -*- coding: utf-8 -*-
"""Keys and logins of the account written into the device's own (hidden) settings (S5, T8, T9).

The server sends them by addon setting id; a secret id it does not send is not in the account and is cleared here.
The Webshare session `token` is the device's own (T9): it is cleared when the login changes, so the addon's existing
re-login runs with the account's username and password. Values are never logged."""
from wcs.account import schema, state

DEVICE_ONLY = ('token', 'vinyl_status')


def apply(values, previous_login=None):
    import xbmcaddon
    addon = xbmcaddon.Addon(state.ADDON_ID)
    ids = schema.secret_ids() or []
    login_before = (addon.getSetting('wsuser'), addon.getSetting('wspass'))
    changed = 0
    for sid in ids:
        value = str(values.get(sid) or '')
        if addon.getSetting(sid) != value:
            addon.setSetting(sid, value)
            changed += 1
    if values.get('vinyl_status') is not None and addon.getSetting('vinyl_status') != values['vinyl_status']:
        addon.setSetting('vinyl_status', values['vinyl_status'])
    if (addon.getSetting('wsuser'), addon.getSetting('wspass')) != login_before:
        addon.setSetting('token', values.get('token') or '')          # a new login: the device logs in again itself
    elif values.get('token') and not addon.getSetting('wsuser'):
        addon.setSetting('token', values['token'])                    # a shared session without a login (T9)
    if changed:
        refresh_status(addon)
    return changed


def restore_webshare_token(addon=None):
    """A signed-in device without its own Webshare login plays with the account's session token (T9). When that token
    is gone from the device or Webshare refused it, the account's keys are fetched again. True: a token is there now."""
    import xbmcaddon
    if not state.signed_in():
        return False
    addon = addon or xbmcaddon.Addon(state.ADDON_ID)
    if addon.getSetting('wsuser') and addon.getSetting('wspass'):
        return False                                   # an own login: the addon's usual re-login applies
    import time
    import xbmcgui
    home = xbmcgui.Window(10000)
    try:
        last = float(home.getProperty('milionar.account.ws_restore') or 0)
    except ValueError:
        last = 0
    if time.time() - last >= 60:                       # an account without Webshare does not wait on every play
        home.setProperty('milionar.account.ws_restore', str(time.time()))
        try:
            from wcs.account import sync
            sync.fetch_secrets()
        except Exception:
            return False
    # the caller's Addon object keeps the values it read: hand it the token the account's keys wrote
    token = xbmcaddon.Addon(state.ADDON_ID).getSetting('token')
    if token and addon.getSetting('token') != token:
        addon.setSetting('token', token)
    return bool(token)


def refresh_status(addon=None):
    """Statuses, provider flags and Home properties after the keys changed (as after a key window)."""
    import xbmcaddon
    addon = addon or xbmcaddon.Addon(state.ADDON_ID)
    for step in (_ai_status, _providers):
        try:
            step(addon)
        except Exception:
            pass


def _ai_status(addon):
    from wcs.ai import accounts
    accounts.sync_status(addon)


def _providers(addon):
    from wcs.skin import actions
    actions.set_provider_properties(addon)


def clear(addon=None):
    """Sign-out: the account's keys leave the device (the local ones come back from the backup)."""
    import xbmcaddon
    addon = addon or xbmcaddon.Addon(state.ADDON_ID)
    for sid in list(schema.secret_ids()) + list(DEVICE_ONLY):
        addon.setSetting(sid, '')
