# -*- coding: utf-8 -*-
"""The pairing of this Kodi with an account (docs/plan/milionar-account/040 §1): a code from the server, the phone
approves it on the web, the switch to the account's data (switch.signin). Shared by the account window (ui.PairWindow)
and the account step of the first-run guide (wcs/onboarding/account_step.py).

Everything runs in a background thread that only reports through the view's methods, which set window properties
(never a control). A new code (start) makes the older attempt stale; stop() ends it."""
import threading
import time

import xbmc

from wcs.account import client


def device_name():
    name = xbmc.getInfoLabel('System.FriendlyName') or 'Kodi'
    return name[:80]


class Pairing(object):
    """view: waiting(), code(qr, code, url), expired(), offline(upgrade), signing(percent), paired(user), failed()."""

    def __init__(self, view):
        self.view = view
        self.generation = 0
        self.closing = threading.Event()
        self.thread = None

    def start(self):
        self.generation += 1
        self.closing.clear()
        self.thread = threading.Thread(target=self._run, args=(self.generation,), name='milionar-account-pair', daemon=True)
        self.thread.start()

    def stop(self):
        self.closing.set()

    def _run(self, generation):
        monitor = xbmc.Monitor()
        current = lambda: generation == self.generation and not self.closing.is_set() and not monitor.abortRequested()
        self.view.waiting()
        try:
            _s, started = client.request('POST', 'device/pair/start', {'name': device_name(), 'platform': 'kodi',
                                                                       'app_version': client.version()}, token='', timeout=15)
        except client.AccountError as exc:
            if current():
                self.view.offline(exc.code == 'upgrade')
            return
        if not current():
            return
        self.view.code(started['qr_url'], started['user_code'], started['verify_url'])
        deadline = time.monotonic() + int(started.get('expires_in') or 600)
        interval = max(2, int(started.get('interval') or 2))
        while current():
            if monitor.waitForAbort(interval) or not current():
                return
            if time.monotonic() > deadline:
                break
            try:
                status, body = client.request('POST', 'device/pair/poll', {'device_code': started['device_code']}, token='', timeout=10)
            except client.AccountError as exc:
                if exc.code == 'gone':
                    break
                continue                                    # offline for a moment: poll again
            if status == 200 and body.get('token'):
                if current():
                    self._signin(body)
                else:
                    self._discard(body['token'])         # closed in the same moment: no unused device in the account
                return
        if current():
            self.view.expired()

    @staticmethod
    def _discard(token):
        try:
            client.request('POST', 'sync/logout', {'reason': 'user'}, token=token, timeout=10)
        except client.AccountError:
            pass

    def _signin(self, body):
        from wcs.account import switch
        self.view.signing(0)                             # the switch runs to its end: nothing cancels it
        user = body.get('user') or {}
        ok = switch.signin(body['token'], body.get('device_id', ''), user, lambda percent, _text='': self.view.signing(percent))
        if ok:
            self.view.paired(user)
        else:
            self.view.failed()
