# 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.metadata import MediaMetadata


class AutoplayCountdownDialog(xbmcgui.WindowXMLDialog):
    ACTION_PLAY_NOW = 1
    ACTION_CANCEL_AUTOPLAY = 2
    ACTION_TIMEOUT = 3
    ACTION_DISMISS = 4  # Zavrit dialog, nechat dohrat

    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

    @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',
                'notifications/premium/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
        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)
        self.setProperty(
            'WCS.Autoplay.MetaLine',
            self._compose_meta_line(
                self.next_episode_season_episode,
                self.next_episode_year_only,
                self.next_episode_rating_only,
            ),
        )

        # 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
        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()
        if self._has_control(103):
            self.setFocusId(103)
        else:
            self.setFocusId(120)

    def _has_control(self, control_id):
        try:
            self.getControl(control_id)
            return True
        except Exception:
            return False

    @staticmethod
    def _compose_meta_line(season_episode="", year="", rating=""):
        """Sestaví meta řádek (SxxExx • rok • ★ hodnocení) s barvami pro premium styl."""
        parts = [part for part in (season_episode, year) if part]
        separator = '  •  '
        text = f'[COLOR FF7F7F86]{separator}[/COLOR]'.join(
            f'[COLOR FFC9CAD0]{part}[/COLOR]' for part in parts
        )
        if rating:
            colored_rating = f'[COLOR FFF2DD56]{rating}[/COLOR]'
            if text:
                text += f'[COLOR FF7F7F86]{separator}[/COLOR]{colored_rating}'
            else:
                text = colored_rating
        return text

    def _populate_action_buttons(self):
        """Naplní pill-shaped akční tlačítka (list control 103).

        Premium styl používá pevná tlačítka v XML, list 103 v něm není.
        """
        try:
            action_list = self.getControl(103)
        except Exception:
            xbmc.log(
                "[plugin.video.wcs] AutoplayCountdownDialog: No action list control 103, dialog uses XML buttons",
                level=xbmc.LOGINFO,
            )
            return
        try:
            action_list.reset()
            buttons = [
                ('play_now', 'Přehrát'),
                ('stop', 'Ukončit'),
                ('dismiss', 'Zavřít'),
            ]
            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 in (120, 121, 122):  # Premium styl - pevná tlačítka v XML
            action_ids = {120: 'play_now', 121: 'stop', 122: 'dismiss'}
            self._handle_control_action(action_ids[controlId])
        elif controlId == 103:
            item = self.getControl(103).getSelectedItem()
            if not item:
                return
            self._handle_control_action(item.getProperty('action_id'))

    def _handle_control_action(self, action_id):
        if action_id == 'play_now':
            self.user_action = self.ACTION_PLAY_NOW
            self._stop_countdown()
            self.close()
        elif action_id == 'stop':
            self.user_action = self.ACTION_CANCEL_AUTOPLAY
            self._stop_countdown()
            self.close()
        elif action_id == 'dismiss':
            self.user_action = self.ACTION_DISMISS
            self._stop_countdown()
            self.close()

    def onAction(self, action):
        if action.getId() in (xbmcgui.ACTION_PREVIOUS_MENU, xbmcgui.ACTION_NAV_BACK):
            # BACK/ESC = pouze zavrit dialog (jako Zavrit tlacitko)
            if self.user_action is None:
                self.user_action = self.ACTION_DISMISS
            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.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)
            self.close()

        self._stop_countdown()

    def _stop_countdown(self):
        self.is_running = False

    def get_user_action(self):
        return self.user_action
