# -*- coding: utf-8 -*-
"""
trakt_progress_window.py
WindowXML dialog pro Trakt Device Code autorizaci.

ARCHITEKTURA:
  - doModal() musí být zavolán na HLAVNÍM (plugin) vlákně
  - polling loop běží v BACKGROUND THREADU a volá win.update() / win.request_close()

Závisí na:
  resources/skins/Default/1080i/progress.xml
  resources/skins/Default/media/fenlight_common/{white,circle}.png

Kontroly v XML:
  ID 200   = image  (QR kód)
  ID 2000  = label  (nadpis)
  ID 2001  = textbox (instrukce)
  ID 5000  = progress bar

Použití:
    win = TraktProgressWindow.create(heading='...', icon='/path/qr.png')
    # Spustit polling v background threadu
    t = threading.Thread(target=_poll, args=(win,), daemon=True)
    t.start()
    win.doModal()   # blokuje na hlavním vlákně dokud se okno nezavře
    # Po návratu zkontrolovat win.is_canceled() / win.auth_success
"""
import threading
import xbmc
import xbmcgui
import xbmcaddon
from xbmcvfs import translatePath

ADDON       = xbmcaddon.Addon('plugin.video.mmirousek_v3')
_ADDON_PATH = translatePath(ADDON.getAddonInfo('path'))
_XML_FILE   = 'progress.xml'


class TraktProgressWindow(xbmcgui.WindowXMLDialog):
    """Custom XML dialog s QR kódem, textem a progress barem pro Trakt auth."""

    def __init__(self, *args, **kwargs):
        self._heading      = kwargs.pop('heading', 'Trakt – Přihlášení')
        self._icon         = kwargs.pop('icon', '')
        self._content      = kwargs.pop('content', '')
        self._canceled     = False
        self.auth_success  = False
        self._ready        = threading.Event()  # onInit() proběhl
        super().__init__(*args, **kwargs)

    # ── Kodi lifecycle ────────────────────────────────────────────────────────
    def onInit(self):
        """Volá Kodi po otevření okna – nastavíme prvky a signalizujeme ready."""
        try: self.getControl(2000).setLabel(self._heading)
        except Exception: pass

        try: self.getControl(2001).setText(self._content)
        except Exception: pass

        if self._icon:
            try: self.getControl(200).setImage(self._icon, useCache=False)
            except Exception: pass

        try: self.getControl(5000).setPercent(0)
        except Exception: pass

        self._ready.set()

    def onAction(self, action):
        """BACK / ESC / STOP → zrušení."""
        if action.getId() in (
            xbmcgui.ACTION_NAV_BACK,
            xbmcgui.ACTION_PREVIOUS_MENU,
            xbmcgui.ACTION_STOP,
        ):
            self._canceled = True
            self.close()

    # ── Veřejné API ───────────────────────────────────────────────────────────
    def wait_ready(self, timeout: float = 5.0) -> bool:
        """Počká až onInit() nastaví prvky. Vrátí True pokud proběhlo OK."""
        return self._ready.wait(timeout=timeout)

    def update(self, content: str, progress_pct: int) -> None:
        """Aktualizuje text a progress bar z libovolného vlákna."""
        if not self._ready.is_set():
            return
        try: self.getControl(2001).setText(content)
        except Exception: pass
        try:
            self.getControl(5000).setPercent(max(0.0, min(100.0, float(progress_pct))))
        except Exception: pass

    def set_qr(self, path: str) -> None:
        """Nastaví QR kód obrázek z libovolného vlákna."""
        if not self._ready.is_set():
            return
        try: self.getControl(200).setImage(path, useCache=False)
        except Exception: pass

    def request_close(self) -> None:
        """Zavře okno z background vlákna (polling loop)."""
        try: self.close()
        except Exception: pass

    def is_canceled(self) -> bool:
        return self._canceled

    # ── Tovární metoda ────────────────────────────────────────────────────────
    @classmethod
    def create(cls, heading: str = 'Trakt – Přihlášení',
               icon: str = '', content: str = '') -> 'TraktProgressWindow':
        return cls(_XML_FILE, _ADDON_PATH,
                   heading=heading, icon=icon, content=content)
