# wcs/playback/dialogs/countdown.py
# AutoplayCountdownDialog -- countdown dialog pro autoplay další epizody

import xbmc
import xbmcgui
import xbmcaddon
import threading
import time

from wcs.playback.dialogs.base_game_dialog import GameDialogMixin
from wcs.playback.dialogs.media_info import CLOSE_DIALOG_STATES
from wcs.playback.metadata import MediaMetadata


class AutoplayCountdownDialog(GameDialogMixin, xbmcgui.WindowXMLDialog):
    ACTION_PLAY_NOW = 1
    ACTION_CANCEL_AUTOPLAY = 2
    ACTION_TIMEOUT = 3

    def __init__(self, xmlFilename, addonPath, skin="Default", theme="Default",
                 show_countdown_at=25, next_episode_title="", next_episode_season_episode="", next_episode_thumb="",
                 series_name="", series_tmdb_id="", series_fanart="", current_episode_plot="", next_episode_rating="",
                 next_episode_rating_only="", next_episode_year_only="", timeout_callback=None):
        super().__init__()
        self.countdown_duration = show_countdown_at
        self.next_episode_title = next_episode_title
        self.next_episode_season_episode = next_episode_season_episode
        self.next_episode_thumb = next_episode_thumb
        self.series_name = series_name
        self.series_tmdb_id = series_tmdb_id
        self.series_fanart = series_fanart
        self.current_episode_plot = current_episode_plot
        self.next_episode_rating = next_episode_rating
        self.next_episode_rating_only = next_episode_rating_only
        self.next_episode_year_only = next_episode_year_only
        self.user_action = None
        self.countdown_thread = None
        self.is_running = False
        self.player = xbmc.Player()
        self.timeout_callback = timeout_callback

        # Herní panel -- GameDialogMixin
        self.init_game_state()

    @staticmethod
    def get_dialog_xml_filename():
        try:
            addon = xbmcaddon.Addon()
            style_index = int(addon.getSetting('dialog_style') or 0)
            style_files = [
                'notifications/classic/DialogAutoplayCountdown.xml',
                'notifications/modern/DialogAutoplayCountdown.xml',
                'notifications/minimal/DialogAutoplayCountdown.xml',
            ]
            filename = style_files[style_index] if 0 <= style_index < len(style_files) else style_files[0]
            xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Using style index '{style_index}' -> {filename}", level=xbmc.LOGINFO)
            return filename
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Error getting dialog style, using default: {e}", level=xbmc.LOGWARNING)
            return 'notifications/classic/DialogAutoplayCountdown.xml'

    def onInit(self):
        xbmc.log("[plugin.video.wcs] AutoplayCountdownDialog: Initializing with dynamic countdown", level=xbmc.LOGINFO)

        # Properties pro XML
        self.setProperty('WCS.Autoplay.NextEpisode.Title', self.next_episode_title)
        self.setProperty('WCS.Autoplay.NextEpisode.SeasonEpisode', self.next_episode_season_episode)
        self.setProperty('WCS.Autoplay.NextEpisode.Thumb', MediaMetadata._clean_url(self.next_episode_thumb))
        self.setProperty('WCS.Autoplay.NextEpisode.Rating', self.next_episode_rating)
        self.setProperty('WCS.Autoplay.NextEpisode.RatingOnly', self.next_episode_rating_only)
        self.setProperty('WCS.Autoplay.NextEpisode.YearOnly', self.next_episode_year_only)

        # Sériálové properties pro herní panel
        self.setProperty('WCS.Autoplay.SeriesTitle', self.series_name)
        self.setProperty('WCS.Autoplay.SeriesTMDBID', self.series_tmdb_id)
        self.setProperty('WCS.Autoplay.SeriesFanart', MediaMetadata._clean_url(self.series_fanart))
        self.setProperty('WCS.Autoplay.EpisodeDescription', self.current_episode_plot)

        # Inicializace countdown
        self.setProperty('WCS.Autoplay.CountdownTime', str(self.countdown_duration))
        self.setProperty('WCS.Autoplay.Progress', '0')
        try:
            progress_control = self.getControl(105)
            if progress_control:
                progress_control.setPercent(0)
        except Exception:
            pass

        # Akční tlačítka (pill-shaped list)
        self._populate_action_buttons()

        self.is_running = True
        self.countdown_thread = threading.Thread(target=self._dynamic_countdown_worker)
        self.countdown_thread.daemon = True
        self.countdown_thread.start()
        self.setFocusId(103)

    def _populate_action_buttons(self):
        """Naplní pill-shaped akční tlačítka (list control 103)."""
        try:
            action_list = self.getControl(103)
            action_list.reset()
            buttons = [
                ('play_now', 'Přehrát'),
                ('play_game', 'Hrát hru'),
                ('cancel', 'Zrušit'),
            ]
            for action_id, label in buttons:
                item = xbmcgui.ListItem(label)
                item.setProperty('action_id', action_id)
                action_list.addItem(item)
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Failed to populate action buttons: {e}", level=xbmc.LOGERROR)

    def onClick(self, controlId):
        if controlId == 103:  # Akční tlačítka (pill-shaped list)
            item = self.getControl(103).getSelectedItem()
            if not item:
                return
            action_id = item.getProperty('action_id')
            if action_id == 'play_now':  # Přehrát ihned
                self.user_action = self.ACTION_PLAY_NOW
                self._stop_countdown()
                self.close()
            elif action_id == 'cancel':  # Zrušit autoplay
                self.user_action = self.ACTION_CANCEL_AUTOPLAY
                self._stop_countdown()
                self.close()
            elif action_id == 'play_game':  # Hrát hru – toggle
                self.game_visible = not self.game_visible
                self.setProperty('WCS.Autoplay.ShowGame', 'true' if self.game_visible else 'false')
                if self.game_visible and not self.game_controller:
                    self.start_game()
                    try:
                        self.setFocus(self.getControl(301))
                    except Exception:
                        pass
                elif not self.game_visible and self.game_controller:
                    self.game_controller = None
        elif controlId in [301, 302, 303, 304] and self.game_controller:
            choice_index = controlId - 301
            current_state = self.game_controller.current_game_state
            if choice_index == 3 and current_state in CLOSE_DIALOG_STATES:
                # Zavřít herní panel
                self.game_visible = False
                self.setProperty('WCS.Autoplay.ShowGame', 'false')
                self.game_controller = None
                if self.user_action == self.ACTION_TIMEOUT:
                    # Už došlo k timeoutu → rovnou zavři dialog
                    self.user_action = None
                    self.close()
                else:
                    try:
                        self.setFocus(self.getControl(103))
                    except Exception:
                        pass
            else:
                self.game_controller.make_choice(choice_index)

    def onAction(self, action):
        if action.getId() in (xbmcgui.ACTION_PREVIOUS_MENU, xbmcgui.ACTION_NAV_BACK):
            if self.user_action is None:
                self.user_action = self.ACTION_CANCEL_AUTOPLAY
            self._stop_countdown()
            self.close()

    def _dynamic_countdown_worker(self):
        xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Starting countdown from {self.countdown_duration}s to 0", level=xbmc.LOGINFO)
        countdown_time = self.countdown_duration
        while self.is_running and countdown_time > 0:
            try:
                if not self.player.isPlaying():
                    xbmc.log("[plugin.video.wcs] AutoplayCountdownDialog: Player stopped, ending countdown", level=xbmc.LOGINFO)
                    break
                progress = ((self.countdown_duration - countdown_time) / self.countdown_duration) * 100
                progress = max(0, min(100, progress))
                self.setProperty('WCS.Autoplay.CountdownTime', str(int(countdown_time)))
                self.setProperty('WCS.Autoplay.Progress', str(int(progress)))
                try:
                    progress_control = self.getControl(105)
                    if progress_control:
                        progress_control.setPercent(progress)
                except Exception:
                    pass
                countdown_time -= 1
                time.sleep(1)
            except Exception as e:
                xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Error in countdown: {e}", level=xbmc.LOGERROR)
                break

        if countdown_time <= 0 and self.is_running:
            self.user_action = self.ACTION_TIMEOUT
            self._stop_countdown()
            if self.game_visible and self.game_controller:
                if self.timeout_callback:
                    try:
                        self.timeout_callback()
                    except Exception as e:
                        xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Error calling timeout callback: {e}", level=xbmc.LOGERROR)
                return
            else:
                xbmc.executebuiltin("Action(Back)")

        self._stop_countdown()

    def _stop_countdown(self):
        self.is_running = False

    def get_user_action(self):
        return self.user_action

    # --- GameDialogMixin bridge metody ---

    def _game_prefix(self):
        return 'WCS.Autoplay.Game'

    def _game_title_for_controller(self):
        return self.series_name

    def _game_plot_for_controller(self):
        return self.current_episode_plot

    def _game_genre_for_controller(self):
        return ''

    def _game_media_type_for_controller(self):
        return 'series'

    def _game_episode_title(self):
        return self.next_episode_title

    # Override: chybový text s navigací na Button3 (Zavřít)
    def show_game_error(self, message):
        prefix = self._game_prefix()
        try:
            self.setProperty(f'{prefix}.Text', f"Chyba: {message}\n\nStiskni 'Zavřít' pro návrat.")
            self.setProperty(f'{prefix}.Button1', "")
            self.setProperty(f'{prefix}.Button2', "")
            self.setProperty(f'{prefix}.Button3', "Zavřít")
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error showing game error: {e}", level=xbmc.LOGERROR)
