# -*- coding: utf-8 -*-
"""Is this device signed in to a Milionář account? Cheap (one setting read, cached 2 s per process).

Every other module of wcs.account is imported only when this says yes (K3, docs/plan/milionar-account/900)."""
import threading
import time

ADDON_ID = 'plugin.video.milionar'
TOKEN = 'account_token'
NAME = 'account_name'
EMAIL = 'account_email'
DEVICE = 'account_device_id'
SERVER = 'account_server'
HOME_LABEL = 'milionar.account.label'          # Window(Home) property: label of the account item (menu 1108, S24)
_cache = {'at': 0.0, 'value': False}
_lock = threading.Lock()
_local = threading.local()


def _addon():
    import xbmcaddon
    return xbmcaddon.Addon(ADDON_ID)


def signed_in():
    now = time.monotonic()
    with _lock:
        if now - _cache['at'] < 2.0:
            return _cache['value']
    try:
        value = bool(_addon().getSetting(TOKEN))
    except Exception:
        value = False
    with _lock:
        _cache.update(at=now, value=value)
    return value


def invalidate():
    with _lock:
        _cache['at'] = 0.0


def account_name():
    try:
        return _addon().getSetting(NAME) if signed_in() else ''
    except Exception:
        return ''


class applying(object):
    """Within this block the store writes come from the server (a pull or a switch): they are not queued again."""

    def __enter__(self):
        _local.depth = getattr(_local, 'depth', 0) + 1
        return self

    def __exit__(self, *exc):
        _local.depth -= 1
        return False


def is_applying():
    return getattr(_local, 'depth', 0) > 0
