# -*- coding: utf-8 -*-
"""HTTP client of the Milionář account (docs/plan/milionar-account/020 §1, WEB docs/plan/account-sync/04-protocol.md).

One requests.Session per process. Every call has a timeout, learns the server-time offset (T3) and never logs headers,
bodies, tokens or keys. Errors become AccountError with a code the caller can act on:
  unauthorized (401: token revoked / user disabled), upgrade (426), offline (network, timeout, 5xx), invalid (4xx).
"""
import json
import threading
import time

from wcs.account import state

PROTOCOL = '1'
DEFAULT_SERVER = 'https://hosting.pilsfree.net/chudy/milionar/'     # S29: the Hub (production); the Mac instance is development only
CONNECT_S = 5
_session = None
_lock = threading.Lock()


class AccountError(Exception):
    def __init__(self, code, status=0, message=''):
        super(AccountError, self).__init__(message or code)
        self.code = code
        self.status = status


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


def server():
    """The account server (T16): the hidden `account_server` setting (harnesses) or the default."""
    try:
        value = _addon().getSetting(state.SERVER).strip()
    except Exception:
        value = ''
    value = value or DEFAULT_SERVER
    return value if value.endswith('/') else value + '/'


def version():
    try:
        return _addon().getAddonInfo('version')
    except Exception:
        return '0'


def session():
    global _session
    with _lock:
        if _session is None:
            import requests
            _session = requests.Session()
        return _session


def _log(message):
    try:
        import xbmc
        xbmc.log('[Milionář Account] {}'.format(message), xbmc.LOGINFO)
    except Exception:
        pass


def remember_offset(server_time_ms):
    """offset = server time - local time, kept in sync_state (read by hooks.now_ms)."""
    try:
        offset = int(server_time_ms) - int(time.time() * 1000)
        from wcs.library2 import store
        with store.tx() as conn:
            conn.execute("INSERT OR REPLACE INTO sync_state(key, value) VALUES('offset', ?)", (str(offset),))
    except Exception:
        pass


def request(method, path, body=None, token=None, timeout=10, params=None, stream=False):
    """JSON request to `<server>api/<path>`; returns (status, data). `token` None = the device token."""
    import requests
    url = server() + 'api/' + path.lstrip('/')
    headers = {'X-Milionar-Sync': PROTOCOL, 'X-Milionar-Client': 'kodi/' + version(), 'Accept': 'application/json'}
    if token is None:
        token = _addon().getSetting(state.TOKEN)
    if token:
        headers['Authorization'] = 'Bearer ' + token
    try:
        response = session().request(method, url, json=body, params=params, headers=headers,
                                     timeout=(CONNECT_S, timeout), stream=stream)
    except requests.RequestException as exc:
        raise AccountError('offline', 0, type(exc).__name__)
    if stream:
        return response
    return _finish(method, path, response)


def _finish(method, path, response, text=None):
    status = response.status_code
    try:
        body = text if text is not None else response.text
        data = json.loads(body) if body else {}
    except ValueError:
        data = {}
    if isinstance(data, dict) and data.get('server_time'):
        remember_offset(data['server_time'])
    if status in (200, 201, 202, 204, 304):
        return status, data
    _log('{} {} -> {}'.format(method, path.split('?')[0], status))
    if status == 401:
        raise AccountError('unauthorized', status)
    if status == 426:
        raise AccountError('upgrade', status)
    if status == 410:
        raise AccountError('gone', status)
    if status == 429:
        raise AccountError('slow_down', status)
    if status >= 500:
        raise AccountError('offline', status)
    code = data.get('error', {}).get('code') if isinstance(data.get('error'), dict) else data.get('code')
    raise AccountError(code or 'invalid', status)


def long_poll(since, wait, abort):
    """GET sync/changes, waiting up to `wait` s on the server (T4)."""
    return poll('sync/changes', {'since': int(since), 'wait': int(wait)}, abort)


def poll(path, params, abort):
    """A long-poll GET of `path`. The server sends a space every second while it waits (`hb=1`), so the read never
    blocks longer than ~2 s and `abort()` (Kodi's stop) ends the call within that (T4)."""
    params = dict(params, hb=1)
    response = request('GET', path, params=params, timeout=4, stream=True)
    chunks = []
    try:
        for chunk in response.iter_content(chunk_size=None, decode_unicode=False):
            if abort():
                raise AccountError('aborted')
            if chunk:
                chunks.append(chunk)
    except AccountError:
        raise
    except Exception as exc:
        raise AccountError('offline', 0, type(exc).__name__)
    finally:
        response.close()
    text = b''.join(chunks).decode('utf-8', 'replace').strip()
    return _finish('GET', path, response, text=text)
