# -*- coding: utf-8 -*-
"""The modern game card showing the server's game: the same adapter interface as MillionaireMyTVAdapter
(start, act, screen, focus_target, retire, cleanup), but no controller here. It renders the `WCS.Game.*` properties
the server computed (WEB shared/games/view.ts `viewProperties`, oracle-proven against wcs/games/game_view.py) and sends
the player's keys. While the card is open it long-polls the game, so ChatGPT's moves show at once."""
import threading

import xbmc

from wcs.account import client
from wcs.games import designs
from wcs.games.remote import api, intents

EXIT_FOCUS = 9691                      # "stay in the game" of the exit prompt
ANSWER_FIRST_ID = 9500


def art(view):
    """The title's own properties of the card (Name, Year, Genre, Poster, Fanart)."""
    from wcs.library2 import tmdb
    title = view.get('title') or {}
    poster = tmdb.POSTER + title['poster'] if title.get('poster') else ''
    fanart = tmdb.BACKDROP + title['fanart'] if title.get('fanart') else poster
    return {'WCS.Game.Name': title.get('name', ''), 'WCS.Game.Year': str(title.get('year') or ''),
            'WCS.Game.Genre': title.get('genre', ''), 'WCS.Game.Poster': poster, 'WCS.Game.Fanart': fanart}


class RemoteAdapter(object):
    def __init__(self, dialog, view):
        self.dialog = dialog
        self.view = view
        self._shown = {}
        self._lock = threading.Lock()
        self._retired = False
        self._busy = False

    # ---- the interface of the card (wcs/games/DialogMilionarGame.py) ----

    def start(self):
        self.apply(self.view, force=True)
        threading.Thread(target=self._follow, name='milionar-remote-card', daemon=True).start()

    def act(self, intent):
        command = intents.command(intent)
        if command:
            self._send(*command)

    def back(self):
        self._send(*intents.back(self.screen(), self._exit()))

    def screen(self):
        return self.view.get('screen') or 'title'

    def focus_target(self):
        if self._exit():
            return EXIT_FOCUS
        if self.screen() == 'question':
            return self._first_answer()
        return designs.MODERN.primary.get(self.screen(), designs.MODERN.menu_primary)

    def retire(self):
        self._retired = True

    def cleanup(self):
        for name in list(self._shown):
            self.dialog.clearProperty(name)
        self._shown.clear()

    # ---- the server's game ----

    def apply(self, view, force=False):
        """Show a newer view of the game (only the properties that changed); a closed game closes the card."""
        with self._lock:
            if self._retired:
                return
            before = (self.screen(), self._exit(), self._lives())
            if not force and view.get('version') == self.view.get('version'):
                return
            self.view = view
            if not view.get('open'):
                self.dialog._close_game_dialog()
                return
            values = dict(view.get('properties') or {}, **art(view))
            values['WCS.Game.ButtonsReady'] = 'true'
            for name, value in values.items():
                if self._shown.get(name) != value:
                    self._shown[name] = value
                    self.dialog.setProperty(name, value)
            if force or before != (self.screen(), self._exit(), self._lives()):
                self._focus()

    def _follow(self):
        monitor = xbmc.Monitor()
        failures = 0
        while not self._retired and not monitor.abortRequested():
            try:
                self.apply(api.listen(self.view.get('version'), lambda: self._retired or monitor.abortRequested()))
                failures = 0
            except client.AccountError as exc:
                if exc.code == 'aborted':
                    return
                failures += 1
                if monitor.waitForAbort(min(10, failures)):
                    return

    def _send(self, action, answer):
        if self._busy:                      # one key at a time: a second press would meet a stale version
            return
        self._busy = True
        threading.Thread(target=self._press, args=(action, answer), daemon=True).start()

    def _press(self, action, answer):
        try:
            self.apply(api.press(self.view.get('version'), action, answer))
        except client.AccountError as exc:
            xbmc.log('[Milionář] remote game {}: {}'.format(action, exc.code), xbmc.LOGINFO)
            try:                            # the game moved on (ChatGPT was faster): show where it is now
                self.apply(api.current())
            except client.AccountError:
                pass
        finally:
            self._busy = False

    def _exit(self):
        return (self.view.get('properties') or {}).get('WCS.Game.Exit') == 'true'

    def _lives(self):
        properties = self.view.get('properties') or {}
        return tuple(properties.get('WCS.Game.' + key, '') for key in ('Life5050Used', 'LifeTipUsed', 'LifeAudienceUsed'))

    def _first_answer(self):
        properties = self.view.get('properties') or {}
        for index, letter in enumerate(intents.LETTERS):
            if properties.get('WCS.Game.State' + letter) != 'removed':
                return ANSWER_FIRST_ID + index
        return ANSWER_FIRST_ID

    def _focus(self):
        target = self.focus_target()
        if target == EXIT_FOCUS:
            try:
                self.dialog.setFocusId(EXIT_FOCUS)
            except Exception:
                pass
        else:
            self.dialog._delayed_focus(target, delay=0.15)
