# wcs/playback/dialogs/managers.py
# Manažeři dialogů a singleton factory funkce

import xbmc
import xbmcaddon
import threading

from wcs.playback.dialogs.media_info import MediaInfoDialog
from wcs.playback.dialogs.countdown import AutoplayCountdownDialog


# ---------------- Managers (API kompatibilita) ----------------

class MovieInfoManager:
    def __init__(self, addon):
        self.addon = addon

    @staticmethod
    def get_dialog_xml_filename():
        return MediaInfoDialog._get_dialog_xml_filename_for_media('movie')

    def show_movie_info(self, movie_title, movie_year="", movie_thumb="", rating="",
                        plot="", tmdb_id="", fanart="", genre="", director="", runtime=""):
        xbmc.log(f"[plugin.video.wcs] MovieInfoManager: Showing movie info dialog for {movie_title} ({movie_year})", level=xbmc.LOGINFO)
        dialog_xml = MovieInfoManager.get_dialog_xml_filename()
        dialog = MediaInfoDialog(
            dialog_xml,
            self.addon.getAddonInfo('path'),
            media_type='movie',
            movie_title=movie_title,
            movie_year=movie_year,
            movie_thumb=movie_thumb,
            rating=rating,
            plot=plot,
            tmdb_id=tmdb_id,
            fanart=fanart,
            genre=genre,
            director=director,
            runtime=runtime,
        )
        xbmc.log("[plugin.video.wcs] MovieInfoManager: About to show dialog modal", level=xbmc.LOGINFO)
        dialog.doModal()
        xbmc.log("[plugin.video.wcs] MovieInfoManager: Dialog modal completed", level=xbmc.LOGINFO)
        del dialog


class EpisodeInfoManager:
    def __init__(self, addon):
        self.addon = addon

    @staticmethod
    def get_dialog_xml_filename():
        return MediaInfoDialog._get_dialog_xml_filename_for_media('series')

    def show_episode_info(self, series_name, episode_title, season_number, episode_number,
                          episode_thumb="", rating="", year="", plot="", tmdb_id="", fanart=""):
        xbmc.log(
            f"[plugin.video.wcs] EpisodeInfoManager: Showing episode info dialog for {series_name} S{season_number}E{episode_number}",
            level=xbmc.LOGINFO,
        )
        dialog_xml = EpisodeInfoManager.get_dialog_xml_filename()
        dialog = MediaInfoDialog(
            dialog_xml,
            self.addon.getAddonInfo('path'),
            media_type='series',
            series_name=series_name,
            episode_title=episode_title,
            season_number=season_number,
            episode_number=episode_number,
            episode_thumb=episode_thumb,
            rating=rating,
            year=year,
            plot=plot,
            tmdb_id=tmdb_id,
            fanart=fanart,
        )
        xbmc.log("[plugin.video.wcs] EpisodeInfoManager: About to show dialog modal", level=xbmc.LOGINFO)
        dialog.doModal()
        xbmc.log("[plugin.video.wcs] EpisodeInfoManager: Dialog modal completed", level=xbmc.LOGINFO)
        del dialog


class AutoplayManager:
    ACTION_PLAY_NOW = 1
    ACTION_CANCEL_AUTOPLAY = 2
    ACTION_TIMEOUT = 3

    def __init__(self, addon):
        self.addon = addon
        self.autoplay_enabled = False
        try:
            self.countdown_seconds = int(addon.getSetting('autoplay_countdown_seconds') or '30')
            if self.countdown_seconds < 10:
                self.countdown_seconds = 10
            elif self.countdown_seconds > 120:
                self.countdown_seconds = 120
        except (ValueError, TypeError):
            self.countdown_seconds = 30
        try:
            self.trigger_seconds = int(addon.getSetting('autoplay_trigger_seconds') or '5')
            if self.trigger_seconds < 3:
                self.trigger_seconds = 3
            elif self.trigger_seconds >= self.countdown_seconds:
                self.trigger_seconds = max(3, self.countdown_seconds - 5)
        except (ValueError, TypeError):
            self.trigger_seconds = 5
        self.countdown_duration = self.countdown_seconds - self.trigger_seconds
        if self.countdown_duration <= 0:
            self.countdown_duration = 5
        self.current_series_info = None
        self.current_episode_info = None

    def set_autoplay_enabled(self, enabled):
        self.autoplay_enabled = enabled
        xbmc.log(f"[plugin.video.wcs] AutoplayManager: Autoplay {'enabled' if enabled else 'disabled'}", level=xbmc.LOGINFO)

    def set_current_episode(self, series_name, season, episode, tmdb_id=None, current_quality=None):
        self.current_series_info = {
            'name': series_name,
            'tmdb_id': tmdb_id,
        }
        self.current_episode_info = {
            'season': season,
            'episode': episode,
            'quality': current_quality,
        }

    def get_next_episode_info(self):
        if not self.current_series_info or not self.current_episode_info:
            return None
        series_name = self.current_series_info['name']
        current_season = self.current_episode_info['season']
        current_episode = self.current_episode_info['episode']
        try:
            from wcs.library.LibraryManager import get_next_episode_metadata_from_library
            next_metadata = get_next_episode_metadata_from_library(series_name, current_season, current_episode)
            if next_metadata:
                season_episode = f"S{next_metadata['season_number']:02d}E{next_metadata['episode_number']:02d}"
                rating_formatted = ""
                rating_only_text = ""
                year_only_text = ""
                if next_metadata.get('episode_rating') and next_metadata['episode_rating'] > 0:
                    try:
                        rating_float = float(next_metadata['episode_rating'])
                        rating_formatted = f"{rating_float:.1f}"
                    except (ValueError, TypeError):
                        rating_formatted = str(next_metadata['episode_rating'])
                    rating_only_text = f"★ {rating_formatted}/10"
                    if next_metadata.get('episode_year'):
                        rating_text = f"★ {rating_formatted}/10 • {next_metadata['episode_year']}"
                        year_only_text = next_metadata['episode_year']
                    else:
                        rating_text = f"★ {rating_formatted}/10"
                else:
                    rating_text = next_metadata.get('episode_year', '') if next_metadata.get('episode_year') else ""
                    if next_metadata.get('episode_year'):
                        year_only_text = next_metadata['episode_year']
                return {
                    'title': next_metadata['episode_title'],
                    'season_episode': season_episode,
                    'thumb': next_metadata.get('episode_thumb', ''),
                    'season': next_metadata['season_number'],
                    'episode': next_metadata['episode_number'],
                    'rating': rating_text,
                    'rating_only': rating_only_text,
                    'year_only': year_only_text,
                }
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] AutoplayManager: Error getting next episode metadata: {e}", level=xbmc.LOGERROR)
            return None
        # Fallback
        next_episode = current_episode + 1
        season_episode = f"S{current_season:02d}E{next_episode:02d}"
        return {
            'title': 'Další epizoda',
            'season_episode': season_episode,
            'thumb': '',
            'season': current_season,
            'episode': next_episode,
            'rating': '',
            'rating_only': '',
            'year_only': '',
        }

    def show_countdown_dialog(self, current_remaining_time=None):
        if not self.autoplay_enabled:
            return None
        next_episode = self.get_next_episode_info()
        if not next_episode:
            xbmc.log("[plugin.video.wcs] AutoplayManager: No next episode found", level=xbmc.LOGINFO)
            return None
        if current_remaining_time is not None:
            real_countdown_duration = current_remaining_time - self.trigger_seconds
            real_countdown_duration = max(3, min(real_countdown_duration, self.countdown_duration))
        else:
            real_countdown_duration = self.countdown_duration
        xbmc.log(
            f"[plugin.video.wcs] AutoplayManager: Showing countdown dialog - countdown duration: {real_countdown_duration}s (from {self.countdown_seconds}s before end to {self.trigger_seconds}s before end)",
            level=xbmc.LOGINFO,
        )
        def timeout_callback():
            try:
                def play_next():
                    import time
                    time.sleep(0.5)
                    from wcs.playback.PlayerMonitor import get_player_monitor
                    player_instance = get_player_monitor()
                    if player_instance:
                        player_instance._handle_next_episode(is_manual=False)
                thread = threading.Thread(target=play_next)
                thread.daemon = True
                thread.start()
            except Exception as e:
                xbmc.log(f"[plugin.video.wcs] AutoplayManager: Error in timeout callback: {e}", level=xbmc.LOGERROR)
        dialog_xml = AutoplayCountdownDialog.get_dialog_xml_filename()
        dialog = AutoplayCountdownDialog(
            dialog_xml,
            self.addon.getAddonInfo('path'),
            show_countdown_at=real_countdown_duration,
            next_episode_title=next_episode['title'],
            next_episode_season_episode=next_episode.get('season_episode', ''),
            next_episode_thumb=next_episode['thumb'],
            series_name=self.current_series_info['name'],
            series_tmdb_id=str(self.current_series_info.get('tmdb_id', '')),
            series_fanart='',
            current_episode_plot='',
            next_episode_rating=next_episode.get('rating', ''),
            next_episode_rating_only=next_episode.get('rating_only', ''),
            next_episode_year_only=next_episode.get('year_only', ''),
            timeout_callback=timeout_callback,
        )
        dialog.doModal()
        user_action = dialog.get_user_action()
        del dialog
        return user_action


# ---------------- Singleton factory funkce ----------------

_movie_info_manager = None
_episode_info_manager = None
_autoplay_manager = None


def get_movie_info_manager():
    global _movie_info_manager
    if _movie_info_manager is None:
        addon = xbmcaddon.Addon()
        _movie_info_manager = MovieInfoManager(addon)
    return _movie_info_manager


def get_episode_info_manager():
    global _episode_info_manager
    if _episode_info_manager is None:
        addon = xbmcaddon.Addon()
        _episode_info_manager = EpisodeInfoManager(addon)
    return _episode_info_manager


def get_autoplay_manager():
    global _autoplay_manager
    if _autoplay_manager is None:
        addon = xbmcaddon.Addon()
        _autoplay_manager = AutoplayManager(addon)
    return _autoplay_manager
