# -*- coding: utf-8 -*-
"""The plugin action `milionar_remote`: the modern game card showing the game ChatGPT opened (G2: a playing video
stops first). One card at a time: Window(Home) property `milionar.game.remote` is set while it is open."""
import time

import xbmc
import xbmcgui

from wcs.account import client
from wcs.games import designs
from wcs.games.DialogMilionarGame import ACTION_NAV_BACK, ACTION_PREVIOUS_MENU, MilionarGameModal
from wcs.games.remote import api
from wcs.games.remote.adapter import RemoteAdapter

OPEN = 'milionar.game.remote'


def is_open():
    return bool(xbmcgui.Window(10000).getProperty(OPEN))


class RemoteGameModal(MilionarGameModal):
    """The card of the local game, but every key goes to the server's game (no settings, no Příběh)."""

    def __new__(cls, view):
        return super(RemoteGameModal, cls).__new__(cls, design=designs.MODERN)     # never the classic card

    def __init__(self, view):
        title = view.get('title') or {}
        super(RemoteGameModal, self).__init__(title=title.get('name', ''), genre=title.get('genre', ''),
                                              media_type=title.get('media', 'movie'), year=title.get('year', ''),
                                              design=designs.MODERN, mode='millionaire')
        self.story_available = False
        self.mode = 'millionaire'
        self._view = view

    def onInit(self):
        self.setProperty('WCS.Game.Remote', 'true')       # the card hides what belongs to the local game
        super(RemoteGameModal, self).onInit()

    def _new_adapter(self):
        return RemoteAdapter(self, self._view)

    def onClick(self, controlId):
        intent = self._design.clicks.get(controlId)
        if intent and self._adapter:
            self._adapter.act(intent)

    def onAction(self, action):
        if action.getId() in (ACTION_PREVIOUS_MENU, ACTION_NAV_BACK):
            if self._adapter:
                self._adapter.back()
            return
        super(RemoteGameModal, self).onAction(action)


def _stop_playback():
    player = xbmc.Player()
    if not player.isPlaying():
        return
    player.stop()
    monitor = xbmc.Monitor()
    for _ in range(30):                 # the game card opens once the video is gone (at most 3 s)
        if not player.isPlaying() or monitor.waitForAbort(0.1):
            return


def run():
    home = xbmcgui.Window(10000)
    if home.getProperty(OPEN):
        return
    home.setProperty(OPEN, repr(time.time()))
    try:
        view = api.current()
        if not view.get('open'):
            return
        _stop_playback()
        modal = RemoteGameModal(view)
        modal.doModal()
        del modal
    except client.AccountError as exc:
        xbmc.log('[Milionář] remote game: {}'.format(exc.code), xbmc.LOGINFO)
    finally:
        home.clearProperty(OPEN)
