# -*- coding: utf-8 -*-
"""Pro tebe of the account (docs/plan/milionar-account/050, T26): a fresh snapshot another device of the account built
is downloaded instead of computed; a device that builds one uploads it. The server not answering, or no fresh
snapshot: the addon computes it itself as always (S25). Signed out this module is never used."""
from wcs.account import client, state

TIMEOUT = 20


def fetch_fresh(due):
    """The account's snapshot when it is fresh for this device (`due(snapshot)` says nothing is due), else None."""
    from wcs.foryou import engine
    try:
        status, data = client.request('GET', 'sync/foryou', timeout=TIMEOUT)
    except client.AccountError as exc:
        if exc.status != 404:
            client._log('Pro tebe of the account unavailable: {}'.format(exc.code))
        return None
    snapshot = (data or {}).get('snapshot') if status == 200 else None
    if not isinstance(snapshot, dict) or snapshot.get('version') != engine.VERSION:
        return None
    if not isinstance(snapshot.get('modes'), dict) or not isinstance(snapshot.get('items'), dict):
        return None
    if due(snapshot) not in ('', 'signals'):
        return None
    return snapshot


def upload(snapshot):
    try:
        client.request('PUT', 'sync/foryou', {'snapshot': snapshot}, timeout=TIMEOUT)
    except client.AccountError as exc:
        client._log('Pro tebe upload failed: {}'.format(exc.code))


def signed_in():
    return state.signed_in()
