"""The ChatGPT game shown in Kodi (wcs/games/remote, WEB docs/plan/kodi-game): keys -> server commands, the card
renders the server's view, the service opens the card once."""
import os
import sys
import unittest
from unittest import mock

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import kodi_stubs                                           # noqa: E402

kodi_stubs.install()
from wcs.account import client                              # noqa: E402
from wcs.games import designs                               # noqa: E402
from wcs.games.remote import adapter, intents, listener      # noqa: E402

# the commands of the server's game (WEB shared/contracts/remote-game.ts GAME_COMMANDS), without ChatGPT's own
SERVER = {'start', 'rules', 'back', 'next', 'again', 'results', 'retry', 'exit_stay', 'exit_confirm', 'answer',
          'fifty', 'audience', 'tip', 'close'}
LOCAL = ('settings', 'mode_millionaire', 'mode_story', 'story_primary')


def view(version, screen='question', open_=True, **properties):
    props = {'WCS.Game.Screen': screen, 'WCS.Game.Exit': '', 'WCS.Game.StateA': 'normal', 'WCS.Game.StateB': 'normal',
             'WCS.Game.StateC': 'normal', 'WCS.Game.StateD': 'normal'}
    props.update({'WCS.Game.' + key: value for key, value in properties.items()})
    return {'version': version, 'open': open_, 'screen': screen, 'properties': props,
            'title': {'name': 'Matrix', 'year': 1999, 'genre': 'Sci-fi', 'media': 'movie', 'poster': '/p.jpg', 'fanart': '/f.jpg'}}


class Card(kodi_stubs.Window):
    def __init__(self):
        super(Card, self).__init__()
        self.focused = []

    def _delayed_focus(self, control_id, delay=0.5):
        self.focused.append(control_id)

    def _close_game_dialog(self):
        self.closed = True


class IntentTests(unittest.TestCase):
    def test_every_click_of_the_modern_card_is_a_server_command_or_local(self):
        for control, intent in designs.MODERN.clicks.items():
            command = intents.command(intent)
            if command is None:
                self.assertTrue(intent in LOCAL or intent.startswith('set_'), (control, intent))
            else:
                self.assertIn(command[0], SERVER, (control, intent))

    def test_answers_lifelines_and_leaving(self):
        self.assertEqual(intents.command('answer2'), ('answer', 'C'))
        self.assertEqual(intents.command('life5050'), ('fifty', None))
        self.assertEqual(intents.command('lifeaudience'), ('audience', None))
        self.assertEqual(intents.command('home'), ('close', None))
        self.assertIsNone(intents.command('answer9'))

    def test_back(self):
        self.assertEqual(intents.back('question', True), ('exit_stay', None))
        self.assertEqual(intents.back('title', False), ('close', None))
        self.assertEqual(intents.back('question', False), ('back', None))
        self.assertEqual(intents.back('rules', False), ('back', None))


class AdapterTests(unittest.TestCase):
    def test_renders_only_what_changed_and_focuses_by_screen(self):
        card = Card()
        remote = adapter.RemoteAdapter(card, view('a:1'))
        remote.apply(remote.view, force=True)
        self.assertEqual(card.getProperty('WCS.Game.Screen'), 'question')
        self.assertEqual(card.getProperty('WCS.Game.ButtonsReady'), 'true')
        self.assertTrue(card.getProperty('WCS.Game.Poster').endswith('/p.jpg'))
        self.assertEqual(card.focused, [9500])
        remote.apply(view('a:1', 'feedback'))                 # the same version: nothing to do
        self.assertEqual(card.getProperty('WCS.Game.Screen'), 'question')
        remote.apply(view('a:2', 'question', Life5050Used='true', StateA='removed', StateB='removed'))
        self.assertEqual(card.focused[-1], 9502, 'after 50:50 the first answer left')
        remote.apply(view('a:3', 'question', Exit='true'))
        self.assertEqual(card.focus, adapter.EXIT_FOCUS)
        remote.apply(view('a:4', 'feedback'))
        self.assertEqual(card.focused[-1], 9641)
        remote.cleanup()
        self.assertEqual(card.getProperty('WCS.Game.Screen'), '')

    def test_a_closed_game_closes_the_card(self):
        card = Card()
        remote = adapter.RemoteAdapter(card, view('a:1'))
        remote.apply(view('a:2', open_=False))
        self.assertTrue(card.closed)

    def test_a_refused_key_shows_where_the_game_is_now(self):
        card = Card()
        remote = adapter.RemoteAdapter(card, view('a:1'))
        with mock.patch.object(adapter.api, 'press', side_effect=client.AccountError('version_conflict', 409)), \
                mock.patch.object(adapter.api, 'current', return_value=view('a:5', 'feedback')):
            remote._press('answer', 'A')
        self.assertEqual(remote.view['version'], 'a:5')
        self.assertFalse(remote._busy)


class Monitor(object):
    def __init__(self, rounds):
        self.rounds = rounds

    def abortRequested(self):
        self.rounds -= 1
        return self.rounds < 0

    def waitForAbort(self, seconds):
        return False


class ListenerTests(unittest.TestCase):
    def test_a_game_opens_the_card_once(self):
        views = iter([view('a:0', open_=False), view('a:1'), view('a:2'), view('a:3', open_=False)])
        del kodi_stubs.BUILTINS[:]
        with mock.patch.object(listener.api, 'listen', side_effect=lambda after, abort: next(views)):
            listener.loop(Monitor(4), lambda: False)
        self.assertEqual(kodi_stubs.BUILTINS, [listener.URL])

    def test_an_old_server_backs_off(self):
        waits = []
        monitor = Monitor(2)
        monitor.waitForAbort = lambda seconds: waits.append(seconds) or False
        with mock.patch.object(listener.api, 'listen', side_effect=client.AccountError('not_found', 404)):
            listener.loop(monitor, lambda: False)
        self.assertEqual(waits, [2, 4])


if __name__ == '__main__':
    unittest.main()
