# -*- coding: utf-8 -*-
"""Account ops recorded inside the store's own transactions (T5, docs/plan/milionar-account/020 §2).

`record(conn, type, key, payload)` is called by wcs/library2/store.py inside `with tx() as conn`: the op is in
`sync_outbox` exactly when the change is committed. Signed out, or while a pulled change is applied, it does nothing.
A newer `progress` of the same key replaces the queued one; nothing else coalesces (a watched is never dropped)."""
import json
import time
import uuid

from wcs.account import state

WAKE = 'milionar.account.outbox'               # Window(Home) property the push thread watches
_offset = {'value': None, 'at': 0.0}


def offset_ms(conn):
    """The device's learned server-time offset (T3), read at most every 30 s."""
    now = time.monotonic()
    if _offset['value'] is None or now - _offset['at'] > 30:
        row = conn.execute("SELECT value FROM sync_state WHERE key='offset'").fetchone()
        _offset.update(value=int(float(row[0])) if row else 0, at=now)
    return _offset['value']


def now_ms(conn=None):
    base = int(time.time() * 1000)
    if conn is None:
        from wcs.library2 import store
        conn = store.connect()
        try:
            return base + offset_ms(conn)
        finally:
            conn.close()
    return base + offset_ms(conn)


def record(conn, op_type, key, payload=None):
    if state.is_applying() or not state.signed_in():
        return
    at = now_ms(conn)
    data = json.dumps(payload or {}, ensure_ascii=False, separators=(',', ':'))
    if op_type == 'progress':
        conn.execute("DELETE FROM sync_outbox WHERE type='progress' AND key=? AND attempts=0", (key,))
    conn.execute('INSERT INTO sync_outbox(op_id, type, key, at, payload) VALUES(?,?,?,?,?)',
                 (uuid.uuid4().hex, op_type, key, at, data))
    conn.outbox = True


def committed():
    """After the commit: wake the push thread of the service (it may be another process)."""
    try:
        import xbmcgui
        xbmcgui.Window(10000).setProperty(WAKE, repr(time.time()))
    except Exception:
        pass


def watch_key(media_type, tmdb_id, season=None, episode=None):
    if media_type == 'movie':
        return 'movie:{}'.format(int(tmdb_id))
    return 'tv:{}:{}:{}'.format(int(tmdb_id), -1 if season is None else int(season), -1 if episode is None else int(episode))
