# -*- coding: utf-8 -*-
"""The account in the service (docs/plan/milionar-account/030 §6, 020 §5).

start(): an interrupted sign-in / sign-out is finished first (before rows and the sync threads), then the account item
label is published and, signed in, the sync threads start. A Monitor listens for the plugin's notifications:
`account_changed` (a sign-in finished in the plugin) and `account_signout` (the user asked to sign out)."""
import os
import threading

import xbmc

from wcs.account import state

_monitor = None


def _journal_exists():
    from wcs.account import docs
    return os.path.exists(docs._path('account', 'switch.json'))


class AccountMonitor(xbmc.Monitor):
    def __init__(self, abort_monitor):
        super(AccountMonitor, self).__init__()
        self.abort_monitor = abort_monitor

    def reconcile(self):
        """The sync threads follow the account token, whoever changed it (a sign-in in the plugin, a sign-out)."""
        state.invalidate()
        from wcs.account import switch, worker
        if switch.busy():
            return
        if state.signed_in():
            worker.start(self.abort_monitor)
        worker.publish_label()

    def onSettingsChanged(self):
        try:
            import time
            import xbmcgui
            from wcs.account import worker
            xbmcgui.Window(10000).setProperty(worker.SETTINGS_CHANGED, repr(time.time()))
        except Exception:
            pass
        signed = state.signed_in()
        state.invalidate()
        if state.signed_in() != signed or (state.signed_in() and not worker_alive()):
            self.reconcile()

    def onNotification(self, sender, method, data):
        if sender != state.ADDON_ID:
            return
        method = method[6:] if method.startswith('Other.') else method
        if method == 'account_changed':
            self.reconcile()
            if state.signed_in():                      # a sign-in finished: the Home rows of the account follow
                from wcs.account import progress
                progress.begin_signin()
                guide_when_due(self.abort_monitor)     # an account whose guide is open (onboarding D32)
        elif method == 'account_merge':                # S28: this Kodi's data go into the account
            from wcs.account import progress
            progress.begin_merge()
        elif method == 'account_signout':
            threading.Thread(target=self._signout, name='milionar-account-signout', daemon=True).start()

    def _signout(self):
        from wcs.account import switch, ui, worker
        try:
            switch.signout(ask=ui.ask_unsent, monitor=self.abort_monitor)
            import xbmcgui
            xbmcgui.Dialog().notification('Milionář', ui.text(ui.S_SIGNED_OUT), xbmcgui.NOTIFICATION_INFO, 4000)
        except Exception as exc:
            xbmc.log('[Milionář Account] sign-out failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
        worker.publish_label()
        guide_when_due(self.abort_monitor, wait=False)


def guide_when_due(monitor, wait=True):
    """After a switch: the first-run guide, if this device or account has not finished it (onboarding D32)."""
    def run():
        try:
            from wcs.onboarding import launch
            launch.when_due(monitor)
        except Exception as exc:
            xbmc.log('[Milionář Account] guide after the switch failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
    if wait:
        threading.Thread(target=run, name='milionar-account-guide', daemon=True).start()
    else:
        run()


def worker_alive():
    from wcs.account import worker
    return any(thread.is_alive() for thread in worker._threads)


def start(abort_monitor):
    global _monitor
    try:
        if _journal_exists():
            from wcs.account import switch
            switch.resume_if_needed()
        _monitor = AccountMonitor(abort_monitor)
        from wcs.account import worker
        worker.publish_label()
        if state.signed_in():
            worker.start(abort_monitor)
    except Exception as exc:
        xbmc.log('[Milionář Account] start failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
