# -*- coding: utf-8 -*-
"""Sign-in and sign-out: a journaled switch between the device's own data and the account (S3, S4, T11, T13).

DATA/account/switch.json is the journal {op, stage, ...}, written atomically before each stage; every stage can run
again after a crash (resume_if_needed at the service start, before rows and the sync threads):

  sign-in : stage (download into staging/) -> backup (local data -> local_backup/) -> apply (account -> local)
            -> refresh -> done
  sign-out: flush (outbox to the server) -> clear+restore (local_backup/ -> local) -> refresh -> done

Nothing local changes before the account is completely downloaded; a failed download leaves the device as it was."""
import json
import os
import shutil
import sqlite3
import time

from wcs.account import apply, client, docs, schema, secrets, state

USER_TABLES = ('titles', 'movie_state', 'episode_state', 'play_log', 'feedback', 'sync_outbox', 'sync_state')
FILES = ('search_history.json', 'global_watch_history.json', 'ai_recommendations.json', 'favorite_actors.json',
         'favorite_directors.json', 'favorite_writers.json', 'mytv_channels.json', 'mycinema_channels.json', 'ai_usage.db')
FOLDERS = ('mytv_history', 'mycinema_history')
ACCOUNT_SETTINGS = (state.TOKEN, state.DEVICE, state.NAME, state.EMAIL)
EXTRA_SETTINGS = ('token', 'vinyl_status', 'onboarding_step', 'onboarding_genres')


def _dir(*parts):
    return docs._path('account', *parts)


def _journal():
    return docs._read(_dir('switch.json'), None)


def _set_journal(data):
    docs._write(_dir('switch.json'), data)


def busy():
    return os.path.exists(_dir('switch.json'))


def _log(message):
    client._log(message)


def _addon():
    import xbmcaddon
    return xbmcaddon.Addon(state.ADDON_ID)


# --------------------------------------------------------------------------- backup / restore of the local data

def _db_path():
    from wcs.library2 import store
    return store.db_path()


def backup_local():
    """local_backup/: the user tables (+ Pro tebe snapshot), the account-class files and settings of this device."""
    target = _dir('local_backup')
    if os.path.isdir(target):
        shutil.rmtree(target)
    os.makedirs(os.path.join(target, 'files'))
    from wcs.library2 import store
    store.connect().close()                                   # schema up to date before the copy
    conn = sqlite3.connect(_db_path(), timeout=5.0)
    try:
        conn.execute('ATTACH DATABASE ? AS b', (os.path.join(target, 'library_user.db'),))
        for table in USER_TABLES:
            conn.execute('CREATE TABLE b.{0} AS SELECT * FROM main.{0}'.format(table))
        conn.execute("CREATE TABLE b.meta AS SELECT * FROM main.meta WHERE key LIKE 'foryou:%'")
        conn.execute("CREATE TABLE b.flags AS SELECT * FROM main.flags WHERE key NOT LIKE 'widget.rev.%'")
        conn.commit()
        conn.execute('DETACH DATABASE b')
    finally:
        conn.close()
    present = []
    for name in FILES + FOLDERS:
        source = docs._path(name)
        if os.path.isdir(source):
            shutil.copytree(source, os.path.join(target, 'files', name))
            present.append(name)
        elif os.path.isfile(source):
            shutil.copy2(source, os.path.join(target, 'files', name))
            present.append(name)
    addon = _addon()
    ids = set(schema.account_ids()) | set(schema.secret_ids()) | set(EXTRA_SETTINGS)
    values = {sid: addon.getSetting(sid) for sid in sorted(ids)}
    docs._write(os.path.join(target, 'settings.json'), {'values': values, 'files': present})
    os.chmod(os.path.join(target, 'settings.json'), 0o600)


def _columns(conn, schema_name, table):
    return [r[1] for r in conn.execute('PRAGMA {}.table_info({})'.format(schema_name, table))]


def restore_local():
    """The device's own data back from local_backup/ (sign-out). Idempotent."""
    target = _dir('local_backup')
    manifest = docs._read(os.path.join(target, 'settings.json'), {})
    from wcs.library2 import store
    store.connect().close()
    conn = sqlite3.connect(_db_path(), timeout=5.0, isolation_level=None)
    try:
        conn.execute('ATTACH DATABASE ? AS b', (os.path.join(target, 'library_user.db'),))      # outside a transaction
        conn.execute('BEGIN IMMEDIATE')
        try:
            for table in USER_TABLES + ('meta', 'flags'):
                if table == 'meta':
                    conn.execute("DELETE FROM main.meta WHERE key LIKE 'foryou:%'")
                elif table == 'flags':
                    conn.execute("DELETE FROM main.flags WHERE key NOT LIKE 'widget.rev.%'")
                else:
                    conn.execute('DELETE FROM main.{}'.format(table))
                common = [c for c in _columns(conn, 'b', table) if c in _columns(conn, 'main', table)]
                if common:
                    cols = ','.join(common)
                    conn.execute('INSERT OR REPLACE INTO main.{0}({1}) SELECT {1} FROM b.{0}'.format(table, cols))
            conn.execute('COMMIT')
        except Exception:
            conn.execute('ROLLBACK')
            raise
        conn.execute('DETACH DATABASE b')
    finally:
        conn.close()
    present = set(manifest.get('files') or [])
    for name in FILES + FOLDERS:
        live = docs._path(name)
        saved = os.path.join(target, 'files', name)
        if os.path.isdir(live):
            shutil.rmtree(live)
        elif os.path.isfile(live):
            os.remove(live)
        if name in present:
            if os.path.isdir(saved):
                shutil.copytree(saved, live)
            elif os.path.isfile(saved):
                shutil.copy2(saved, live)
    addon = _addon()
    for sid, value in (manifest.get('values') or {}).items():
        if addon.getSetting(sid) != value:
            addon.setSetting(sid, value)


# --------------------------------------------------------------------------- refresh without restarting Kodi

def refresh():
    """Every row, section and widget shows the new side (S4): row revisions, the rows journal, provider flags and
    Home properties, the account label, Pro tebe in the background."""
    from wcs.library2 import store
    from wcs.skin import refresh as skin_refresh
    with store.tx() as conn:
        store.dirty(conn, set(skin_refresh.ALL_ROWS) | {'fy_genres'})
    secrets.refresh_status()
    try:
        from wcs.skin import journal
        journal.request_all()
    except Exception:
        pass
    notify('skin_widgets_refresh')
    from wcs.account import worker
    worker.publish_label()


def _foryou_soon():
    import threading

    def build():
        try:
            from wcs.foryou import service
            service.build_now('account')
        except Exception as exc:
            _log('Pro tebe after the switch failed: {}'.format(type(exc).__name__))
    threading.Thread(target=build, name='milionar-account-foryou', daemon=True).start()


# --------------------------------------------------------------------------- sign-in

def signin(token, device_id, user, progress=None):
    """After the pairing (token from the server). Returns True when the device shows the account."""
    report = progress or (lambda percent, text='': None)
    _set_journal({'op': 'login', 'stage': 'stage', 'at': time.time()})
    staging = _dir('staging')
    try:
        if os.path.isdir(staging):
            shutil.rmtree(staging)
        os.makedirs(staging)
        report(10)
        _s, schema_data = client.request('GET', 'sync/schema', token=token, timeout=20)
        report(25)
        _s, snap = client.request('GET', 'sync/bootstrap', token=token, timeout=90)
        report(55)
        _s, keys = client.request('GET', 'sync/secrets', token=token, timeout=20)
        docs._write(os.path.join(staging, 'schema.json'), schema_data)
        docs._write(os.path.join(staging, 'bootstrap.json'), snap)
        docs._write(os.path.join(staging, 'secrets.json'), keys)
        docs._write(os.path.join(staging, 'account.json'), {'token': token, 'device_id': device_id,
                                                            'name': (user or {}).get('name', ''), 'email': (user or {}).get('email', '')})
        for name in ('secrets.json', 'account.json'):
            os.chmod(os.path.join(staging, name), 0o600)
    except Exception as exc:
        _log('sign-in download failed: {}'.format(getattr(exc, 'code', type(exc).__name__)))
        shutil.rmtree(staging, ignore_errors=True)
        os.remove(_dir('switch.json'))
        try:
            client.request('POST', 'sync/logout', {'reason': 'user'}, token=token, timeout=10)
        except Exception:
            pass
        return False
    _continue_login(report)
    return True


def _continue_login(report):
    with _UserFirst():
        _login_stages(report)


def _login_stages(report):
    staging = _dir('staging')
    journal = _journal() or {}
    clock = [time.time()]

    def lap(name):
        _log('sign-in {} {:.1f} s'.format(name, time.time() - clock[0]))
        clock[0] = time.time()
    if journal.get('stage') in ('stage', 'backup'):
        _set_journal({'op': 'login', 'stage': 'backup'})
        schema.save(docs._read(os.path.join(staging, 'schema.json'), {}))
        report(65)
        backup_local()
        lap('backup')
        _set_journal({'op': 'login', 'stage': 'apply'})
        journal = _journal()
    if journal.get('stage') == 'apply':
        report(75)
        account = docs._read(os.path.join(staging, 'account.json'), {})
        snap = docs._read(os.path.join(staging, 'bootstrap.json'), {})
        schema.save(docs._read(os.path.join(staging, 'schema.json'), {}))
        addon = _addon()
        addon.setSetting(state.TOKEN, account.get('token', ''))
        addon.setSetting(state.DEVICE, account.get('device_id', ''))
        addon.setSetting(state.NAME, account.get('name', ''))
        addon.setSetting(state.EMAIL, account.get('email', ''))
        state.invalidate()
        shutil.rmtree(docs._path('account', 'base'), ignore_errors=True)
        for name in FILES + FOLDERS:
            path = docs._path(name)
            if os.path.isdir(path):
                shutil.rmtree(path)
            elif os.path.isfile(path) and name.endswith('.db'):
                os.remove(path)
        from wcs.library2 import store
        with store.tx() as conn:
            conn.execute('DELETE FROM sync_outbox')
            conn.execute("DELETE FROM sync_state WHERE key != 'offset'")
            conn.execute("DELETE FROM meta WHERE key LIKE 'foryou:%'")
        lap('prepare')
        changes = apply.bootstrap_changes(snap)
        apply.apply_page(changes, int(snap.get('rev') or 0), replace=True)
        lap('apply')
        onboarding = [c for c in changes if c['entity'] == 'onboarding']
        if onboarding:
            docs.apply(onboarding)
        else:
            addon.setSetting('onboarding_step', '')
            addon.setSetting('onboarding_genres', '')
        keys = docs._read(os.path.join(staging, 'secrets.json'), {})
        secrets.apply(keys.get('values') or {})
        with store.tx() as conn:
            conn.execute("INSERT OR REPLACE INTO sync_state(key, value) VALUES('secrets_rev', ?)", (str(int(keys.get('secrets_rev') or 0)),))
        lap('secrets')
        _set_journal({'op': 'login', 'stage': 'refresh'})
    report(90)
    refresh()
    lap('refresh')
    _foryou_soon()
    shutil.rmtree(staging, ignore_errors=True)
    os.remove(_dir('switch.json'))
    report(100)
    _notify_service()
    _log('signed in')


# --------------------------------------------------------------------------- sign-out

def signout(ask=None, push=True, monitor=None, progress=None):
    """Back to the device's own data. `ask(count)` → True to go on when ops could not be sent (S20)."""
    with _UserFirst():
        return _signout(ask, push, monitor, progress)


def _signout(ask=None, push=True, monitor=None, progress=None):
    report = progress or (lambda percent, text='': None)
    from wcs.account import sync, worker
    journal = _journal()
    if not journal or journal.get('op') != 'logout':
        worker.stop()
        _set_journal({'op': 'logout', 'stage': 'flush', 'at': time.time()})
        report(10)
        if push:
            deadline = time.monotonic() + 10
            try:
                sync.queue_docs()
                while time.monotonic() < deadline and sync.push_once():
                    pass
            except Exception:
                pass
            left = sync.outbox_size()
            if left and ask and not ask(left):
                os.remove(_dir('switch.json'))
                if monitor is not None:
                    worker.start(monitor)
                return False
            try:
                client.request('POST', 'sync/logout', {'reason': 'user'}, timeout=10)
            except Exception:
                pass
        _set_journal({'op': 'logout', 'stage': 'restore'})
    elif journal.get('stage') == 'flush':
        # interrupted after the flush (maybe after the server already dropped this device): finish the switch
        worker.stop()
        try:
            client.request('POST', 'sync/logout', {'reason': 'user'}, timeout=10)
        except Exception:
            pass
        _set_journal({'op': 'logout', 'stage': 'restore'})
    report(50)
    if (_journal() or {}).get('stage') == 'restore':
        if os.path.isdir(_dir('local_backup')):
            restore_local()
        else:
            secrets.clear()
        addon = _addon()
        for sid in ACCOUNT_SETTINGS:
            addon.setSetting(sid, '')
        state.invalidate()
        shutil.rmtree(docs._path('account', 'base'), ignore_errors=True)
        _set_journal({'op': 'logout', 'stage': 'refresh'})
    report(85)
    refresh()
    shutil.rmtree(_dir('local_backup'), ignore_errors=True)
    for name in ('schema.json', 'pending_settings.json'):
        if os.path.exists(_dir(name)):
            os.remove(_dir(name))
    os.remove(_dir('switch.json'))
    report(100)
    _notify_service()
    try:
        from wcs.account import progress
        progress.finish()                         # the sign-in's "Připravuji Home" bar is not about this device any more
    except Exception:
        pass
    _log('signed out')
    return True


def remote_signout(monitor, push=True):
    """T13 (service thread): wait while anything plays (a film is never interrupted), then sign out."""
    import xbmc
    while xbmc.getCondVisibility('Player.HasMedia'):
        if monitor.waitForAbort(2):
            return
    signout(push=push, monitor=monitor)
    try:
        import xbmcgui
        addon = _addon()
        xbmcgui.Dialog().notification('Milionář', addon.getLocalizedString(36011), xbmcgui.NOTIFICATION_INFO, 5000)
    except Exception:
        pass


def resume_if_needed():
    """Service start: finish an interrupted switch before anything reads the data. Cheap when nothing is pending."""
    journal = _journal()
    if not journal:
        return False
    _log('resuming {} at {}'.format(journal.get('op'), journal.get('stage')))
    if journal.get('op') == 'login':
        if journal.get('stage') == 'stage':
            shutil.rmtree(_dir('staging'), ignore_errors=True)
            os.remove(_dir('switch.json'))
            return True
        _continue_login(lambda *a: None)
    else:
        signout(push=False)
    return True


def notify(message):
    """JSON-RPC NotifyAll (the NotifyAll builtin drops a message without valid JSON data, wcs/skin/refresh.py)."""
    try:
        import xbmc
        xbmc.executeJSONRPC(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'JSONRPC.NotifyAll',
                                        'params': {'sender': state.ADDON_ID, 'message': message, 'data': {}}}))
    except Exception:
        pass


def _notify_service():
    notify('account_changed')


class _UserFirst(object):
    """While a switch runs the service's background work steps aside (one Python lock, wcs/skin/userfirst.py)."""

    def __enter__(self):
        import threading
        self.done = threading.Event()

        def hold():
            from wcs.skin import userfirst
            while not self.done.wait(1.0):
                userfirst.mark()
        self.thread = threading.Thread(target=hold, name='milionar-account-userfirst', daemon=True)
        self.thread.start()
        return self

    def __exit__(self, *exc):
        self.done.set()
        return False
