# wcs/playback/dialogs/base_game_dialog.py

"""Mixin pro herní panel sdílený mezi info a countdown dialogy.

Parametrizuje property prefix -- každý dialog definuje vlastní prefix
přes metodu _game_prefix(). Tím se eliminuje ~180 řádků duplikovaného kódu.
"""

import xbmc
import threading
import time

from wcs.games.GameManager import GameController


class GameDialogMixin:
    """Sdílené metody pro herní panel v info i countdown dialozích.

    Podtřída MUSÍ definovat:
      - _game_prefix() -> str: prefix pro window properties (např. 'WCS.Game' nebo 'WCS.Autoplay.Game')
      - _game_title_for_controller() -> str: titulek pro GameController
      - _game_plot_for_controller() -> str: plot pro GameController
      - _game_genre_for_controller() -> str: genre pro GameController
      - _game_media_type_for_controller() -> str: 'movie' nebo 'series'

    Volitelně:
      - _game_episode_title() -> str
      - _game_season_number() -> int|None
      - _game_episode_number() -> int|None
    """

    def init_game_state(self):
        """Inicializuje herní stav. Volat v __init__ podtřídy."""
        self.game_visible = False
        self.game_controller = None

    def start_game(self):
        """Spustí herní panel s GameControllerem."""
        prefix = self._game_prefix()
        try:
            media_type = self._game_media_type_for_controller()
            kwargs = {
                'title': self._game_title_for_controller(),
                'plot': self._game_plot_for_controller(),
                'genre': self._game_genre_for_controller(),
                'media_type': media_type,
            }
            if media_type == 'series':
                kwargs['episode_title'] = self._game_episode_title()
                kwargs['season_number'] = self._game_season_number()
                kwargs['episode_number'] = self._game_episode_number()

            self.game_controller = GameController(**kwargs)

            # Title property -- film má prefix "pro", seriál jen název
            if media_type == 'movie':
                self.setProperty(f'{prefix}.Title', f"pro {kwargs['title']}")
            else:
                self.setProperty(f'{prefix}.Title', kwargs['title'])

            self.game_controller.set_ui_callbacks(
                self.update_game_display,
                self.update_game_buttons,
                self.update_game_sidebar,
                self.show_game_error,
                self.set_game_focus,
                self.start_countdown,
            )
            self.game_controller.start_game_selection()
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] {self.__class__.__name__}: Error starting game: {e}", level=xbmc.LOGERROR)
            self.show_game_error("Chyba při spuštění hry.")

    def update_game_display(self, text):
        """Aktualizuje herní text."""
        prefix = self._game_prefix()
        try:
            self.setProperty(f'{prefix}.Text', text)
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error updating game display: {e}", level=xbmc.LOGERROR)

    def update_game_buttons(self, text1, text2, text3, text4=""):
        """Aktualizuje texty herních tlačítek."""
        prefix = self._game_prefix()
        try:
            self.setProperty(f'{prefix}.Button1', text1)
            self.setProperty(f'{prefix}.Button2', text2)
            self.setProperty(f'{prefix}.Button3', text3)
            self.setProperty(f'{prefix}.Button4', text4)
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error updating game buttons: {e}", level=xbmc.LOGERROR)

    def update_game_sidebar(self):
        """Sidebar stub -- dialogy sidebar nepoužívají."""
        pass

    def show_game_error(self, message):
        """Zobrazí chybovou zprávu v herním panelu."""
        prefix = self._game_prefix()
        try:
            self.setProperty(f'{prefix}.Text', f"Chyba: {message}")
            self.setProperty(f'{prefix}.Button1', "Zavřít")
            self.setProperty(f'{prefix}.Button2', "")
            self.setProperty(f'{prefix}.Button3', "")
            self.setProperty(f'{prefix}.Button4', "")
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error showing game error: {e}", level=xbmc.LOGERROR)

    def set_game_focus(self, button_index):
        """Nastaví focus na herní tlačítko."""
        try:
            control_id = 301 + button_index  # 0->301, 1->302, 2->303, 3->304
            self.setFocus(self.getControl(control_id))
        except Exception as e:
            xbmc.log(
                f"[plugin.video.wcs] Error setting game focus to button {button_index}: {e}",
                level=xbmc.LOGERROR,
            )

    def start_countdown(self, seconds, finish_callback):
        """Spustí odpočet vyhodnocení odpovědi v herním panelu."""
        prefix = self._game_prefix()

        def countdown_worker():
            try:
                original_text = ""
                try:
                    original_text = self.getProperty(f'{prefix}.Text')
                except Exception:
                    pass

                if "Vyhodnocení odpovědi..." in original_text:
                    base_text = original_text.split("Vyhodnocení odpovědi...")[0]
                else:
                    base_text = original_text

                for i in range(seconds, 0, -1):
                    countdown_text = base_text + f"Vyhodnocení za {i} sekund..."
                    self.setProperty(f'{prefix}.Text', countdown_text)
                    time.sleep(1)

                finish_callback()
            except Exception as e:
                xbmc.log(f"[plugin.video.wcs] Error in countdown: {e}", level=xbmc.LOGERROR)
                finish_callback()

        countdown_thread = threading.Thread(target=countdown_worker)
        countdown_thread.daemon = True
        countdown_thread.start()

    # ------------------------------------------------------------------
    # Výchozí implementace volitelných metod
    # ------------------------------------------------------------------

    def _game_episode_title(self):
        return ''

    def _game_season_number(self):
        return None

    def _game_episode_number(self):
        return None
