"""One mandatory, durable transition to the single skin; never opens Appearance settings."""
import threading
import time

import xbmc
import xbmcaddon
import xbmcgui

from wcs.skin import family, installer, modular

COMPLETED='skin_unified_v2'
CONFIRMING='milionar.skin.confirming'      # Window(Home): our switch answers Kodi's "Keep skin?" (DialogConfirm.xml)
_busy=threading.Lock()
_next_attempt=0.0


def _confirm(monitor):
    stable=None
    deadline=time.monotonic()+35
    while not monitor.abortRequested() and time.monotonic()<deadline:
        if xbmc.getSkinDir()==family.CLASSIC:
            if xbmc.getCondVisibility('Window.IsActive(yesnodialog)'):
                xbmc.executebuiltin('SendClick(11)',True)
                stable=None
            elif not xbmc.getCondVisibility('System.HasActiveModalDialog'):
                stable=stable or time.monotonic()
                if time.monotonic()-stable>=1:return True
        if monitor.waitForAbort(.1):break
    return False


def run():
    global _next_attempt
    if not _busy.acquire(blocking=False):return False
    addon=xbmcaddon.Addon(installer.ADDON_ID)
    home=xbmcgui.Window(10000)
    try:
        if addon.getSetting(COMPLETED)=='1':return True
        home.setProperty('milionar.skin.choosing','1')
        # Mandatory and immediate: Kodi refuses Home while a modal dialog is open.
        xbmc.executebuiltin('Dialog.Close(all,true)',True)
        xbmc.executebuiltin('ActivateWindow(Home)',True)
        addon.setSetting(modular.MENU,'sidebar')
        addon.setSetting(modular.MATERIAL,'glass')
        previous=xbmc.getSkinDir()
        result=installer.install(addon,force=addon.getSetting(modular.APPLIED)!=modular.key(addon))
        if not result['ready']:return False
        # Kodi asks "Keep skin?" after every skin change (ApplicationSkinHandling::ReloadSkin, Omega); _confirm answers
        # it, our DialogConfirm.xml draws it invisibly meanwhile
        home.setProperty(CONFIRMING,'1')
        try:
            if previous==family.CLASSIC:
                xbmc.executebuiltin('ReloadSkin()',True)
            elif not installer.switch(addon):return False
            if not _confirm(xbmc.Monitor()):return False
        finally:
            home.clearProperty(CONFIRMING)
        from wcs.onboarding import state
        if state.fresh() or state.covered():
            # the guide covers Home (a new install, or an old addon getting the guide, onboarding D27): the Home <onload>
            # chain waits under the cover and Home does not load again after the guide, so the defaults it lacks are
            # written now; the palette below is the only skin load before the guide. An update without the guide
            # leaves them to the skin's own <onload>.
            from wcs.skin import defaults
            defaults.first_setup()
        # Existing palette value, not a newly invented gold or a per-style migration.
        from wcs.skin.appearance import _apply
        if not _apply('gold.xml'):return False
        xbmc.executebuiltin('Skin.SetString(milionar.accent,gold.xml)',True)
        addon.setSetting(modular.APPLIED,modular.key(addon))
        addon.setSetting(COMPLETED,'1')
        installer.retire_legacy()
        return True
    except Exception as exc:
        xbmc.log('[Milionář Skin] unified transition deferred: '+type(exc).__name__,xbmc.LOGWARNING)
        return False
    finally:
        _next_attempt=time.monotonic()+10
        home.clearProperty('milionar.skin.choosing')
        _busy.release()


def offer_startup():
    if xbmcaddon.Addon(installer.ADDON_ID).getSetting(COMPLETED)=='1':return True
    if (_busy.locked() or time.monotonic()<_next_attempt or
        xbmcgui.Window(10000).getProperty('milionar.skin.installing') or
        xbmcgui.Window(10000).getProperty('milionar.skin.choosing')):
        return False
    threading.Thread(target=run,name='milionar-unified-skin',daemon=True).start()
    return False
