# -*- coding: utf-8 -*-
"""Puts a checked package in place of the installed addon (docs/plan/skin-milionar/250-update.md).

Kodi offers Python no way to install a new version of an installed addon, and its own update ignores an addon with
updates switched off. So wcs.skin.update unpacks the release and starts this file as a script of its own: the service
has to stop for the swap and could not stop itself. Only the standard library and Kodi's modules here: the folder this
file came from is the one that moves. When the new version's service does not come up, the old version comes back.
"""
import json
import os
import shutil
import sys
import time

import xbmc
import xbmcgui
import xbmcvfs

ADDON_ID = 'plugin.video.milionar'
ALIVE = 'milionar.service'                  # Home property of the running service (wcs.skin.commands)
STAGE = 'milionar-update'                   # in addons/temp, which Kodi does not scan for addons
PREVIOUS = 'milionar-previous'
REPLACED = 'milionar-replaced'
STOP_S = 20
START_S = 90
DRAIN_S = 20                                # the service's running steps end before it is stopped
WORKING = 'milionar.service.working'        # wcs.skin.userfirst.WORKING
SETTLE_S = 2                                # the stopped service's last threads end
APPLYING = 'milionar.update.applying'       # Home property while apply() runs (a recover() then does nothing)


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


def _enabled(value):
    request = {'jsonrpc': '2.0', 'id': 1, 'method': 'Addons.SetAddonEnabled', 'params': {'addonid': ADDON_ID, 'enabled': value}}
    answer = json.loads(xbmc.executeJSONRPC(json.dumps(request)))
    if 'error' in answer:
        raise OSError(str(answer['error']))


def _wait(monitor, ready, seconds):
    deadline = time.monotonic() + seconds
    while time.monotonic() < deadline:
        if ready():
            return True
        if monitor.waitForAbort(0.25):
            break
    return ready()


def _drain(monitor, home):
    """APPLYING is set: no step of the service's background work starts now (userfirst.give_way). Wait for the running
    ones, so Kodi's stop finds every thread idle: a service still working 5 s after the stop is killed, and on the TV
    that froze Kodi (a row or network step takes seconds there)."""
    started = time.monotonic()
    _wait(monitor, lambda: not home.getProperty(WORKING), DRAIN_S)
    _log('service idle after {:.1f} s{}'.format(time.monotonic() - started,
                                                '' if not home.getProperty(WORKING) else ' (still working)'))


def _stop(monitor, home):
    _drain(monitor, home)
    _enabled(False)
    _wait(monitor, lambda: not home.getProperty(ALIVE), STOP_S)
    monitor.waitForAbort(SETTLE_S)


def _log_end():
    try:
        return os.path.getsize(xbmcvfs.translatePath('special://logpath/kodi.log'))
    except OSError:
        return 0


def _crashed(since, live):
    """The new service.py ended with a Python error: Kodi logs its traceback (a broken release need not keep the
    household waiting the whole START_S)."""
    try:
        with open(xbmcvfs.translatePath('special://logpath/kodi.log'), 'rb') as handle:
            handle.seek(since)
            text = handle.read().decode('utf-8', 'replace')
    except OSError:
        return False
    return 'EXCEPTION Thrown' in text and os.path.join(live, 'service.py') in text


def _start():
    xbmc.executebuiltin('UpdateLocalAddons', True)    # Kodi reads the addon's new version
    _enabled(True)


def _swap(live, incoming, outgoing):
    os.rename(live, outgoing)
    try:
        os.rename(incoming, live)
    except OSError:
        os.rename(outgoing, live)
        raise


def _paths():
    addons = xbmcvfs.translatePath('special://home/addons/')
    temp = os.path.join(addons, 'temp')
    return (os.path.join(addons, ADDON_ID), os.path.join(temp, STAGE), os.path.join(temp, PREVIOUS),
            os.path.join(temp, REPLACED))


def apply(monitor=None, home=None):
    """True when the new version runs."""
    monitor = monitor or xbmc.Monitor()
    home = home or xbmcgui.Window(10000)
    live, stage, previous, replaced = _paths()
    shutil.rmtree(previous, ignore_errors=True)
    shutil.rmtree(replaced, ignore_errors=True)
    home.setProperty(APPLYING, '1')
    try:
        _stop(monitor, home)
        try:
            _swap(live, os.path.join(stage, ADDON_ID), previous)
        except OSError as exc:
            _log('swap failed: {}'.format(exc), xbmc.LOGERROR)
            _start()                                  # the old version goes on; its service reports it (update.resume)
            shutil.rmtree(stage, ignore_errors=True)
            return False
        return _confirm(monitor, home, live, stage, previous, replaced)
    finally:
        home.clearProperty(APPLYING)


def recover(monitor=None, home=None):
    """Home of our skin found the addon switched off or gone: an update cut short (power, a frozen Kodi) between the
    stop and the start. The addon comes back, the version that runs."""
    monitor = monitor or xbmc.Monitor()
    home = home or xbmcgui.Window(10000)
    if home.getProperty(APPLYING):
        return False                                  # an update is in the middle of its swap
    live, stage, previous, replaced = _paths()
    if not os.path.isdir(live):
        for source in (previous, os.path.join(stage, ADDON_ID)):
            if os.path.isdir(source):
                os.rename(source, live)
                break
        else:
            _log('nothing to recover', xbmc.LOGERROR)
            return False
    _log('recovering the addon')
    if not os.path.isdir(previous):
        _start()
        shutil.rmtree(stage, ignore_errors=True)
        return True
    home.setProperty(APPLYING, '1')                   # the new service's tidy keeps `previous` until it is confirmed
    try:
        return _confirm(monitor, home, live, stage, previous, replaced)    # the new version, not yet confirmed
    finally:
        home.clearProperty(APPLYING)


def _confirm(monitor, home, live, stage, previous, replaced):
    """Start the addon in `live`; when its service does not come up, the version in `previous` comes back."""
    since = _log_end()
    _start()
    crashed = []

    def up():
        if not crashed and _crashed(since, live):
            crashed.append(True)
        return bool(home.getProperty(ALIVE)) or bool(crashed)
    if (_wait(monitor, up, START_S) and not crashed) or monitor.abortRequested():
        shutil.rmtree(stage, ignore_errors=True)
        shutil.rmtree(previous, ignore_errors=True)
        return True
    _log('the new service {}: going back'.format('failed' if crashed else 'did not start'), xbmc.LOGERROR)
    _stop(monitor, home)
    _swap(live, previous, replaced)
    _start()
    shutil.rmtree(stage, ignore_errors=True)
    shutil.rmtree(replaced, ignore_errors=True)
    return False


if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == 'recover':
        try:
            _log('recovered' if recover() else 'not recovered')
        except Exception as exc:
            _log('recover failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
            _enabled(True)
        sys.exit()
    _log('installing {}'.format(sys.argv[1] if len(sys.argv) > 1 else ''))
    try:
        _log('installed' if apply() else 'not installed')
    except Exception as exc:
        _log('failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
        _enabled(True)                                # never leave the addon switched off
