# -*- coding: utf-8 -*-
"""Kodi's copy of this addon's texts, made current after an update without a restart (docs/plan/skin-milionar/251).

Kodi 21 reads an addon's strings.po into memory only when Kodi starts, when the GUI language changes, and when Kodi's
own installer installs the addon (`CLocalizeStrings::LoadAddonStrings`, callers `CLangInfo::SetLanguage` and
`CAddonInstallJob::DoWork`, branch Omega). Our update (update_apply.py) swaps the folder itself, so Kodi kept the
texts of the version it started with: a new text was empty (the guide's new button disappeared) and a changed one old,
in Python, in every dialog and skin window (`$ADDON[...]`) and in the addon settings, until Kodi restarted.

strings.po of en_gb carries a stamp of all the addon's texts (STAMP_ID, written by scripts/strings_stamp.py at every
release). The service compares Kodi's copy of it with the file at start: the same, nothing happens (a few ms). Differ,
Kodi reloads its language: the GUI language switches to another one and straight back, both in Kodi's own thread one
after the other (`SetGUILanguage`), so the texts are current about 0.3 s later and nothing shows in the other language;
Kodi then loads the skin twice (each `SetLanguage` queues a `ReloadSkin`). That is done only on a quiet Home: a reload
closes every dialog and Python window, and a closed question counts as answered.

Only the standard library and Kodi's modules here.
"""
import json
import os
import re
import time

import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs

ADDON_ID = 'plugin.video.milionar'
STAMP_ID = 39999
HOME_ID = 10000
UPDATE_WINDOW = 11124                        # wcs.skin.update.WINDOW 1124: Kodi numbers a skin's custom window +10000
NO_DIALOG = 9999                             # Kodi's WINDOW_INVALID: no modal dialog
PYTHON_WINDOWS = 13000                       # Kodi's WINDOW_PYTHON_START: an addon's own window
DEFAULT = 'resource.language.en_gb'          # Kodi's bundled language, always installed
SETTING = 'locale.language'
FALLBACK = 'resource.language.milionar_reload'   # no such addon: CLangInfo::SetLanguage loads the default
MARK = 'milionar.texts.mark'                 # Home: the last queue mark Kodi reached
TRIED = 'milionar.texts.tried'               # Home: the stamp this Kodi session reloaded for (never twice)
PUBLISHED = 'milionar.texts'                 # Home: the stamp Kodi holds; part of every row's signature (journal)
RELOADING = 'milionar.texts.reloading'       # Home: Kodi holds old texts and is about to reload them
REPAIRED = 'texts_repaired'                  # addon_data: the stamp the saved texts were last checked for
JOURNAL = 'texts_refresh.json'               # addon_data: the language to come back to while a reload runs
QUIET_S = 0.6
MARK_S = 60                                  # two skin loads on the TV take ~4 s; Kodi busy elsewhere, longer
HEAD_BYTES = 4096                            # the stamp is the first entry of the file


def _log(message, level=xbmc.LOGINFO):
    xbmc.log('[Milionář Texts] ' + message, level)


def _rpc(method, params=None):
    request = {'jsonrpc': '2.0', 'id': 1, 'method': method}
    if params is not None:
        request['params'] = params
    return json.loads(xbmc.executeJSONRPC(json.dumps(request)))


def _addon_path():
    return xbmcvfs.translatePath(xbmcaddon.Addon(ADDON_ID).getAddonInfo('path'))


def disk_stamp(addon_path=None):
    """The stamp of the texts in the installed folder, '' when the file has none (a version before this)."""
    path = os.path.join(addon_path or _addon_path(), 'resources', 'language', 'resource.language.en_gb', 'strings.po')
    try:
        with open(path, 'rb') as handle:
            head = handle.read(HEAD_BYTES).decode('utf-8', 'replace')
    except OSError:
        return ''
    match = re.search(r'msgctxt "#%d"\s*\nmsgid "([^"]*)"' % STAMP_ID, head)
    return match.group(1) if match else ''


def kodi_stamp():
    """The stamp in Kodi's memory: what Kodi read when it last loaded this addon's texts."""
    return xbmcaddon.Addon(ADDON_ID).getLocalizedString(STAMP_ID)


def stale():
    on_disk = disk_stamp()
    return bool(on_disk) and kodi_stamp() != on_disk


def _journal_path():
    folder = xbmcvfs.translatePath('special://profile/addon_data/{}/'.format(ADDON_ID))
    return os.path.join(folder, JOURNAL)


def _language():
    return ((_rpc('Settings.GetSettingValue', {'setting': SETTING}).get('result') or {}).get('value') or '')


def _other_language(current):
    """Where the GUI language goes for a moment: Kodi's bundled English, or for English any other enabled language."""
    if current != DEFAULT:
        return DEFAULT
    answer = _rpc('Addons.GetAddons', {'type': 'kodi.resource.language', 'enabled': True})
    for addon in (answer.get('result') or {}).get('addons') or []:
        if addon.get('addonid') and addon['addonid'] != current:
            return addon['addonid']
    return FALLBACK                                   # not installed: Kodi loads English for it (measured on the TV)


def _cec_follows_tv():
    """A CEC adapter that takes Kodi's language from the TV: any language change switches that off for good
    (`CPeripherals::OnSettingChanged`, Omega: use_tv_menu_language = false), so the reload is not done there. Its
    settings file in peripheral_data is the only trace Python can see."""
    folder = xbmcvfs.translatePath('special://profile/peripheral_data/')
    try:
        names = os.listdir(folder)
    except OSError:
        return False
    for name in names:
        try:
            with open(os.path.join(folder, name), encoding='utf-8', errors='replace') as handle:
                text = handle.read()
        except OSError:
            continue
        match = re.search(r'id="use_tv_menu_language"\s+value="([^"]*)"', text)
        if match and match.group(1).strip().lower() in ('1', 'true'):
            return True
    return False


def recover_language(monitor=None):
    """Service start: a reload cut short (Kodi quit between the two switches) left the journal; the user's language
    comes back. Kodi saves its settings only on exit, so mostly there is nothing to do."""
    path = _journal_path()
    if not os.path.exists(path):
        return
    try:
        with open(path, encoding='utf-8') as handle:
            wanted = json.load(handle).get('language', '')
        if wanted and _language() != wanted:
            _log('language {} restored after a reload cut short'.format(wanted), xbmc.LOGWARNING)
            xbmc.executebuiltin('SetGUILanguage({})'.format(wanted))
    except Exception as exc:
        _log('journal unreadable: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
    try:
        os.remove(path)
    except OSError:
        pass


def publish():
    """Service start, before any row is built, and after a reload: the stamp Kodi holds, for the rows' signature
    (wcs/skin/journal.py). A row made while Kodi held old texts differs from the current stamp and is built again."""
    try:
        xbmcgui.Window(HOME_ID).setProperty(PUBLISHED, kodi_stamp())
    except Exception as exc:
        _log('publish failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)


def reloading():
    """Kodi holds old texts until the service reloads them: whatever saves texts for good waits (wcs/skin/local.py)."""
    return bool(xbmc.getInfoLabel('Window(Home).Property({})'.format(RELOADING)))


def due():
    """Service start: Kodi holds texts of another version and has not reloaded them for this one in this session.
    True also marks the time until the reload (RELOADING)."""
    try:
        recover_language()
        on_disk = disk_stamp()
        if not on_disk or kodi_stamp() == on_disk:
            return False
        home = xbmcgui.Window(HOME_ID)
        if home.getProperty(TRIED) == on_disk:
            _log('texts still differ after a reload in this session: left as they are', xbmc.LOGERROR)
            return False
        home.setProperty(RELOADING, '1')
        return True
    except Exception as exc:
        _log('check failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
        return False


def repair_once(repair):
    """`repair()` once for every set of texts Kodi holds current: what earlier updates saved while Kodi held old texts
    (an empty row title) is put right. Never while the texts are old."""
    try:
        on_disk = disk_stamp()
        if not on_disk or kodi_stamp() != on_disk:
            return False
        path = os.path.join(os.path.dirname(_journal_path()), REPAIRED)
        try:
            with open(path, encoding='utf-8') as handle:
                if handle.read().strip() == on_disk:
                    return False
        except OSError:
            pass
        repair()
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, 'w', encoding='utf-8') as handle:
            handle.write(on_disk)
        return True
    except Exception as exc:
        _log('repair failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
        return False


def _quiet():
    """Nothing a skin load would close: Home or another skin window, no modal dialog but the update window, no video."""
    window = xbmcgui.getCurrentWindowId()
    dialog = xbmcgui.getCurrentWindowDialogId()
    return (window < PYTHON_WINDOWS and dialog in (NO_DIALOG, UPDATE_WINDOW) and
            not xbmc.getCondVisibility('Player.HasVideo'))


def _wait_quiet(monitor):
    while True:
        if _quiet():
            if monitor.waitForAbort(QUIET_S):
                return False
            if _quiet():
                return True
        elif monitor.waitForAbort(0.25):
            return False


def _mark(monitor, home, number):
    """Queue a mark behind everything Kodi's thread has to do now and wait until it gets there (Kodi's messages run
    in order: ApplicationMessenger, a FIFO)."""
    home.clearProperty(MARK)
    xbmc.executebuiltin('SetProperty({},{},home)'.format(MARK, number))
    waited = 0.0
    while home.getProperty(MARK) != str(number):
        if monitor.waitForAbort(0.05):
            return False
        waited += 0.05
        if waited > MARK_S:
            _log('mark {} not reached in {} s'.format(number, MARK_S), xbmc.LOGWARNING)
            return False
    return True


def _settle(monitor, home):
    """Three marks: the first after the queued switch commands, the second after the language loads they queued (the
    texts are current from there: the skin loads that follow see them), the third after those skin loads."""
    for number in (1, 2, 3):
        if not _mark(monitor, home, number):
            return False
        if number == 2:
            publish()
            home.clearProperty(RELOADING)              # Home's loads now run the saving actions with current texts
    home.clearProperty(MARK)
    return True


def reload_language(monitor, current, other):
    """Kodi reloads its language and every addon's texts: `other` and straight back to `current`, both queued at once,
    so Kodi's thread does both before either skin load and nothing shows in `other`."""
    xbmc.executebuiltin('SetGUILanguage({})'.format(other))
    xbmc.executebuiltin('SetGUILanguage({})'.format(current))
    return _settle(monitor, xbmcgui.Window(HOME_ID))


def refresh(monitor):
    """Reload Kodi's texts of this addon now that they differ from its files. True when Kodi has the current texts (and
    loaded the skin again); False when it was not done (Kodi stopping, nothing to switch to, a failure)."""
    try:
        on_disk = disk_stamp()
        if not _wait_quiet(monitor):
            return False
        if _cec_follows_tv():
            _log('a CEC adapter takes the language from the TV: texts stay until Kodi restarts', xbmc.LOGWARNING)
            return False
        current = _language()
        other = _other_language(current) if current else ''
        if not other:
            _log('no second language to reload with: texts stay until Kodi restarts', xbmc.LOGWARNING)
            return False
        home = xbmcgui.Window(HOME_ID)
        home.setProperty(TRIED, on_disk)
        path = _journal_path()
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, 'w', encoding='utf-8') as handle:
            json.dump({'language': current}, handle)
        started = time.monotonic()
        _log('texts of another version in Kodi ({!r}, files {!r}): reloading via {}'.format(
            kodi_stamp(), on_disk, other))
        finished = reload_language(monitor, current, other)
        if _language() != current:                     # never leave the user in another language
            _log('language is {}: back to {}'.format(_language(), current), xbmc.LOGERROR)
            xbmc.executebuiltin('SetGUILanguage({})'.format(current))
            finished = _settle(monitor, home) and finished
        try:
            os.remove(path)
        except OSError:
            pass
        fresh = kodi_stamp() == on_disk
        _log('texts {} after {:.1f} s (skin loaded again: {})'.format(
            'current' if fresh else 'STILL OLD', time.monotonic() - started, finished),
             xbmc.LOGINFO if fresh else xbmc.LOGERROR)
        return fresh and finished
    except Exception as exc:
        _log('reload failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
        return False
    finally:
        try:
            xbmcgui.Window(HOME_ID).clearProperty(RELOADING)
        except Exception:
            pass
