# -*- coding: utf-8 -*-
"""The server side of the remote game: the screen of this device and its commands (WEB server/sync/game-routes.ts)."""
import uuid

from wcs.account import client

WAIT_S = 20


def listen(after, abort, wait=WAIT_S):
    """The game as this Kodi shows it; waits up to `wait` s while its version is still `after`."""
    return client.poll('sync/game', {'after': after or '', 'wait': int(wait)}, abort)[1]


def current():
    return listen('', lambda: False, wait=0)


def press(version, action, answer=None):
    """One key of the contestant; returns the game after it (a stale `version` raises AccountError version_conflict)."""
    body = {'expectedVersion': version, 'requestId': str(uuid.uuid4()), 'action': action}
    if answer:
        body['answer'] = answer
    return client.request('POST', 'sync/game/command', body)[1]
