# -*- coding: utf-8 -*-
import xbmc
import xbmcgui
import xbmcaddon
from xbmcvfs import translatePath

from resources.lib.utils.log_utils import get_logger

log = get_logger()

ADDON = xbmcaddon.Addon('plugin.video.mmirousek_v3')
_ADDON_PATH = translatePath(ADDON.getAddonInfo('path'))
_XML_FILE = 'script-embuary-person.xml'
_NEXTCALL_PROPERTY = 'plugin.video.mmirousek_v3.person-nextcall'


class PersonInfoWindow(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        self.person = kwargs.pop('person', {}) or {}
        self.movies = kwargs.pop('movies', []) or []
        self.tvshows = kwargs.pop('tvshows', []) or []
        self.images = kwargs.pop('images', []) or []
        super().__init__(*args, **kwargs)

    def onInit(self):
        try:
            self._fill_person()
            self._fill_panel(10052, self.movies, 'movie')
            self._fill_panel(10053, self.tvshows, 'tvshow')
            self._fill_panel(10054, self.images, 'image')
        except Exception as exc:
            log.error(f"[PersonInfoWindow] Chyba v onInit: {exc}")
            raise

    def _fill_person(self):
        container = self.getControl(10051)
        container.reset()

        label = self.person.get('label') or 'Neznámá osoba'
        li = xbmcgui.ListItem(label=label)
        art = self.person.get('art') or {}
        if art:
            li.setArt(art)

        try:
            tag = li.getVideoInfoTag()
            tag.setTitle(label)
            tag.setMediaType('actor')
            biography = self.person.get('biography') or 'Biografie není k dispozici.'
            tag.setPlot(biography)
        except Exception:
            pass

        for key, value in (self.person.get('properties') or {}).items():
            if value not in (None, ''):
                li.setProperty(str(key), str(value))

        container.addItem(li)

    def _make_credit_item(self, item, mediatype):
        label = item.get('label') or 'Bez názvu'
        li = xbmcgui.ListItem(label=label)

        art = item.get('art') or {}
        if art:
            li.setArt(art)

        try:
            tag = li.getVideoInfoTag()
            tag.setTitle(label)
            if item.get('year'):
                tag.setYear(int(item['year']))
            tag.setPlot(item.get('plot') or '')
            tag.setMediaType(mediatype)
        except Exception:
            pass

        if item.get('year'):
            li.setProperty('year', str(item['year']))

        for key, value in (item.get('properties') or {}).items():
            if value not in (None, ''):
                li.setProperty(str(key), str(value))

        return li

    def _make_image_item(self, item):
        label = item.get('label') or 'Foto'
        li = xbmcgui.ListItem(label=label)

        art = item.get('art') or {}
        if art:
            li.setArt(art)
        if item.get('path'):
            li.setProperty('image_path', str(item['path']))
        return li

    def _fill_panel(self, control_id, items, item_type):
        container = self.getControl(control_id)
        container.reset()
        list_items = []

        for item in items:
            if item_type == 'image':
                list_items.append(self._make_image_item(item))
            else:
                list_items.append(self._make_credit_item(item, item_type))

        if list_items:
            container.addItems(list_items)

    def _handle_button_panel(self):
        try:
            panel = self.getControl(100)
            selected_idx = panel.getSelectedPosition()
            if selected_idx is None or selected_idx < 0:
                return

            try:
                item_count = panel.size()
            except Exception:
                item_count = -1

            if item_count >= 0 and selected_idx >= item_count:
                return

            selected_item = panel.getListItem(selected_idx)
            item_label = (selected_item.getLabel() or '').strip()

            if selected_idx == 0 or 'Zav' in item_label:
                self.close()
                return

            if selected_idx == 1 or 'Biografi' in item_label:
                biography = self.person.get('biography') or ''
                if biography:
                    xbmcgui.Dialog().textviewer(self.person.get('label') or 'Biografie', biography)
                else:
                    xbmcgui.Dialog().notification('TMDb', 'Biografie není k dispozici.', xbmcgui.NOTIFICATION_INFO, 2500)
        except Exception as exc:
            log.warning(f"[PersonInfoWindow] Button panel error: {exc}")

    def _handle_credit_panel(self, control_id):
        try:
            panel = self.getControl(control_id)
            selected_idx = panel.getSelectedPosition()
            if selected_idx is None or selected_idx < 0:
                return

            try:
                item_count = panel.size()
            except Exception:
                item_count = -1

            if item_count >= 0 and selected_idx >= item_count:
                return

            selected_item = panel.getListItem(selected_idx)
            target_url = selected_item.getProperty('target_url') or ''
            if not target_url:
                return

            xbmcgui.Window(10000).setProperty(_NEXTCALL_PROPERTY, target_url)
            self.close()
        except Exception as exc:
            log.warning(f"[PersonInfoWindow] Credit panel error controlId={control_id}: {exc}")

    def _handle_image_panel(self):
        try:
            panel = self.getControl(10054)
            selected_idx = panel.getSelectedPosition()
            if selected_idx is None or selected_idx < 0:
                return
            selected_item = panel.getListItem(selected_idx)
            image_path = selected_item.getProperty('image_path') or ''
            if not image_path:
                return
            safe_path = image_path.replace('"', '%22')
            xbmc.executebuiltin(f'ShowPicture("{safe_path}")')
        except Exception as exc:
            log.warning(f"[PersonInfoWindow] Image panel error: {exc}")

    def onAction(self, action):
        action_id = action.getId()

        if action_id in (xbmcgui.ACTION_SELECT_ITEM, xbmcgui.ACTION_MOUSE_LEFT_CLICK):
            focused_id = self.getFocusId()
            if focused_id == 100 or action_id == xbmcgui.ACTION_MOUSE_LEFT_CLICK:
                self._handle_button_panel()
                return
            if focused_id in (10052, 10053):
                self._handle_credit_panel(focused_id)
                return
            if focused_id == 10054:
                self._handle_image_panel()
                return

        if action_id in (
            xbmcgui.ACTION_NAV_BACK,
            xbmcgui.ACTION_PREVIOUS_MENU,
            xbmcgui.ACTION_STOP,
            xbmcgui.ACTION_PARENT_DIR,
        ):
            self.close()

    def onClick(self, controlId):
        if controlId == 100:
            self._handle_button_panel()
            return
        if controlId in (10052, 10053):
            self._handle_credit_panel(controlId)
            return
        if controlId == 10054:
            self._handle_image_panel()

    @classmethod
    def show_info(cls, person, movies=None, tvshows=None, images=None):
        win = cls(
            _XML_FILE,
            _ADDON_PATH,
            'Default',
            '1080i',
            person=person or {},
            movies=movies or [],
            tvshows=tvshows or [],
            images=images or [],
        )
        win.doModal()
        del win