import xbmc
import xbmcgui
import xbmcaddon

from wcs.metadata import TMDbClient as tmdb_handler
from wcs import utils


class DirectorDialog(xbmcgui.WindowXMLDialog):
    def __init__(self, xmlFilename, addonPath, skin="Default", theme="Default", director_id=None):
        super(DirectorDialog, self).__init__()
        self.director_id = director_id
        self.addon = xbmcaddon.Addon()

    def onInit(self):
        if not self.director_id:
            from wcs.ui import UI as ui
            ui.popinfo("Chyba: ID režiséra nebylo předáno do dialogu.", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_ERROR)
            self.close()
            return

        director_data = tmdb_handler.get_director_details(self.director_id)
        if not director_data:
            from wcs.ui import UI as ui
            ui.popinfo(f"Nepodařilo se načíst detaily pro režiséra ID: {self.director_id}", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING)
            self.close()
            return

        self.setProperty('WCS.Director.Name', director_data.get('name', ''))
        profile_path = director_data.get('profile_path')
        if profile_path:
            self.setProperty('WCS.Director.Profile', f"https://image.tmdb.org/t/p/w342{profile_path}")
        else:
            self.setProperty('WCS.Director.Profile', '')
        self.setProperty('WCS.Director.Bio', director_data.get('biography', ''))
        self.setProperty('WCS.Director.Department', director_data.get('known_for_department', ''))
        self.setProperty('WCS.Director.Birthday', director_data.get('birthday', ''))
        self.setProperty('WCS.Director.PlaceOfBirth', director_data.get('place_of_birth', ''))

        known_credits = director_data.get('known_credits')
        if known_credits is None:
            movie_credits = director_data.get('movie_credits', {})
            crew = movie_credits.get('crew', [])
            known_credits = len(crew) if crew else ''
        self.setProperty('WCS.Director.KnownCredits', str(known_credits))

        gender_map = {'0': 'Neznámé', '1': 'Žena', '2': 'Muž', '3': 'Jiné'}
        gender_val = str(director_data.get('gender', '0'))
        self.setProperty('WCS.Director.Gender', gender_map.get(gender_val, 'Neznámé'))
        also_known_as = director_data.get('also_known_as', [])
        self.setProperty('WCS.Director.AlsoKnownAs', '\n'.join(also_known_as) if also_known_as else '')

        self._director_name = director_data.get('name', '')
        self._director_department = director_data.get('known_for_department', '')
        self._director_bio = director_data.get('biography', '')

        movies = tmdb_handler.get_creator_movies(self.director_id)
        panel = self.getControl(5000)
        if not panel:
            xbmc.log(f"{self.addon.getAddonInfo('id')}: Panel s ID 5000 nebyl nalezen v DialogDirectorDetails.xml", xbmc.LOGERROR)
            self.close()
            return
        panel.reset()
        list_items = []

        add_fav_label = "Přidat režiséra do oblíbených"
        add_fav_item = xbmcgui.ListItem(add_fav_label)
        director_photo = f"https://image.tmdb.org/t/p/w500{profile_path}" if profile_path else 'DefaultActor.png'
        add_fav_item.setArt({'icon': director_photo, 'thumb': director_photo, 'poster': director_photo})
        add_fav_item.setProperty('is_add_favorite', '1')
        add_fav_item.setProperty('director_name', self._director_name)
        add_fav_item.setProperty('director_department', self._director_department)
        add_fav_item.setProperty('director_bio', self._director_bio)
        list_items.append(add_fav_item)

        game_item = xbmcgui.ListItem(label="Hrát hru s režisérem")
        game_item.setArt({'thumb': director_photo, 'icon': director_photo, 'poster': director_photo})
        game_item.setProperty('is_start_director_game', '1')
        game_item.setProperty('tmdb_id', str(self.director_id))
        list_items.append(game_item)

        for movie in movies:
            if not movie.get('id') or not movie.get('title'):
                continue
            li_label = movie['title']
            li = xbmcgui.ListItem(li_label)
            poster_path = movie.get('poster_path')
            thumb_url = f"https://image.tmdb.org/t/p/w92{poster_path}" if poster_path else ""
            poster_url = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ""
            art_data = {'thumb': thumb_url, 'icon': thumb_url, 'poster': poster_url}
            art_data = {k: v for k, v in art_data.items() if v}
            if art_data:
                li.setArt(art_data)
            year_str = str(movie.get('release_date', ''))[:4] if movie.get('release_date') else ''
            plot = movie.get('overview', '')
            vote_average = movie.get('vote_average')
            rating_str = f"{vote_average:.1f}" if isinstance(vote_average, (float, int)) and vote_average > 0 else ""
            director = movie.get('director', '')
            writer = movie.get('writer', '')
            info_video = {
                'plot': plot, 'plotoutline': plot, 'title': li_label,
                'originaltitle': movie.get('original_title', li_label),
                'year': int(year_str) if year_str else 0,
                'rating': float(vote_average) if isinstance(vote_average, (float, int)) and vote_average > 0 else 0.0,
                'director': director, 'writer': writer,
            }
            utils.set_video_info_tag(li, info_video)
            li.setProperty('year', year_str)
            li.setProperty('tmdb_id', str(movie['id']))
            if rating_str:
                li.setProperty('rating_text', rating_str)
            list_items.append(li)
        if list_items:
            panel.addItems(list_items)
            self.setFocus(panel)
            try:
                panel.selectItem(0)
            except Exception as e:
                xbmc.log(f"[WCS - DirectorDialog] Error selecting item 0: {e}", xbmc.LOGERROR)
        else:
            xbmc.log(f"[WCS - DirectorDialog] No items to add to panel after processing movies.", xbmc.LOGINFO)

    def onClick(self, controlID):
        if controlID == 5010 or controlID == 5000:
            panel_ctrl = self.getControl(5000)
            if not panel_ctrl:
                xbmc.log(f"[WCS - DirectorDialog] Panel control 5000 not found in onClick!", xbmc.LOGERROR)
                return
            selected_item = panel_ctrl.getSelectedItem()
            if selected_item:
                if selected_item.getProperty('is_start_director_game') == '1':
                    from wcs.games.DialogWcsTextGame import TextGameWindow
                    director_data = tmdb_handler.get_director_details(self.director_id)
                    if not director_data:
                        from wcs.ui import UI as ui
                        ui.popinfo("Nepodařilo se načíst detaily režiséra.", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_ERROR)
                        return
                    profile_path = director_data.get('profile_path')
                    fanart_url = f"https://image.tmdb.org/t/p/w780{profile_path}" if profile_path else ''
                    window = TextGameWindow(
                        "games/DialogWcsTextGame.xml",
                        self.addon.getAddonInfo('path'),
                        "Default",
                        title=director_data.get('name', ''),
                        fanart=fanart_url,
                        plot=director_data.get('biography', '')[:500],
                        genre='',
                        media_type='director',
                        actor_data=director_data,
                        banner_fanart=fanart_url,
                        episode_title="",
                        season_number=None,
                        episode_number=None
                    )
                    window.doModal()
                    del window
                    return
                if selected_item.getProperty('is_add_favorite') == '1':
                    from wcs.ui.UI import add_director_to_favorites
                    director_data = tmdb_handler.get_director_details(self.director_id)
                    director_name = director_data.get('name', '') if director_data else ''
                    add_director_to_favorites(self.addon, self.director_id, director_name)
                    return
                tmdb_id = selected_item.getProperty('tmdb_id')
                item_label = selected_item.getLabel()
                if tmdb_id:
                    dialog = xbmcgui.Dialog()
                    options = [
                        "Přidat do Moje filmy",
                        "Přidat do knihovny Kodi",
                        "Zobrazit detaily",
                        "Přehrát",
                        "Zrušit"
                    ]
                    dialog_title = f"Akce: {item_label}"
                    choice = dialog.select(dialog_title, options)
                    if choice == 0:
                        from wcs.ui.UI import add_movie_item_to_list
                        add_movie_item_to_list(self.addon, tmdb_id, item_label)
                    elif choice == 1:
                        from wcs.library import LibraryManager as library
                        library.check_settings_and_add_item({'media_type': 'movie', 'movie_id': tmdb_id}, self.addon)
                    elif choice == 2:
                        detail_url = f"plugin://{self.addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={tmdb_id}"
                        xbmc.executebuiltin(f"RunPlugin({detail_url})")
                        self.close()
                    elif choice == 3:
                        title = item_label or ''
                        year = selected_item.getProperty('year') or ''
                        poster = selected_item.getArt('poster') or ''
                        fanart = ''
                        rating = selected_item.getProperty('rating_text') or ''
                        genre = ''
                        director = ''
                        runtime = ''
                        plot = selected_item.getProperty('plot') or ''
                        from wcs.utils import search_and_play_movie
                        search_and_play_movie(title, year, plot, poster, fanart, rating, genre, director, runtime, self.addon)
                    return
        elif controlID == 5001:
            pass
        else:
            xbmc.log(f"[WCS - DirectorDialog] Click on unhandled controlID: {controlID}", xbmc.LOGINFO)

    def onAction(self, action):
        if action.getId() == xbmcgui.ACTION_NAV_BACK or action.getId() == xbmcgui.ACTION_PREVIOUS_MENU:
            self.close()


