# -*- coding: utf-8 -*-
"""The account step of the first-run guide (docs/plan/onboarding/000-plan.md D29, WEB account-sync S2, S28, S30).

A mixin of the guide window (wizard.Guide): the QR code, the code and the address on the right, the status line, and
the pairing (wcs/account/pairing.py) in the background. The pairing's thread only sets properties; every move to
another step happens on a click, in the window's own thread. Signed in, the step says so (or offers the merge of this
Kodi's own data, S28) and the user goes on with one press. The guide covers Home meanwhile, so no skin reload closes it."""
from wcs.account import pairing

B1, B2 = 11, 12
S_WITHOUT, S_NEW_CODE, S_CONTINUE = 36005, 36007, 35837
S_WAITING, S_SIGNING, S_SIGNED_IN, S_EXPIRED, S_OFFLINE, S_UPGRADE = 36008, 36009, 36010, 36012, 36013, 36015
S_MERGE_TITLE, S_MERGE_TEXT, S_MERGE, S_ACCOUNT_ONLY = 36038, 36039, 36040, 36041


class AccountStep(object):
    """Phases: 'waiting' (a code shown), 'retry' (expired / offline), 'signing', 'signed', 'merge'."""

    def init_account(self):
        self.pairing = pairing.Pairing(self)
        self.phase = ''

    # ------------------------------------------------------------------ the step

    def show_account(self):
        """Kicker, title and text come from wizard.S like every step's."""
        self.account_path = True
        self.clear_code()
        self.phase = 'waiting'
        self.buttons(self.text(S_WITHOUT))
        self.focus(B1)
        self.pairing.start()

    def clear_code(self):
        for name in ('ob.qr', 'ob.code', 'ob.url'):
            self.setProperty(name, '')

    def click_account(self, control):
        if self.phase == 'signing':
            return                                       # the switch runs; it is never cut off
        if self.phase == 'signed' and control == B1:
            self.signed_in_continue()
        elif self.phase == 'merge' and control in (B1, B2):
            if control == B1:
                from wcs.account import ui as account_ui
                account_ui._merge()
            self.signed_in_continue()
        elif self.phase == 'retry' and control == B1:
            self.clear_code()
            self.phase = 'waiting'
            self.buttons(self.text(S_WITHOUT))
            self.focus(B1)
            self.pairing.start()
        elif (self.phase == 'waiting' and control == B1) or (self.phase == 'retry' and control == B2):
            self.leave_account(self.without_account)

    def back_account(self):
        """Zpět: Vítej, where the account is chosen (D31). Signed in, the step only goes on."""
        if self.phase == 'signing':
            return
        if self.phase in ('signed', 'merge'):
            self.signed_in_continue()
            return
        self.leave_account(lambda: self.show('welcome'))

    def leave_account(self, then):
        self.pairing.stop()
        self.phase = ''
        self.account_path = False
        self.clear_code()
        then()

    def stop_account(self):
        self.pairing.stop()

    # ------------------------------------------------------------------ the pairing's view (its thread: properties only)

    def waiting(self):
        self.status(self.text(S_WAITING), 'busy')

    def code(self, qr, code, url):
        self.setProperty('ob.qr', qr)
        self.setProperty('ob.code', code)
        self.setProperty('ob.url', url)

    def expired(self):
        self.retry(S_EXPIRED)

    def offline(self, upgrade):
        self.retry(S_UPGRADE if upgrade else S_OFFLINE)

    def failed(self):
        self.retry(S_OFFLINE)

    def retry(self, string_id):
        self.clear_code()
        self.status(self.text(string_id), 'error')
        self.buttons(self.text(S_NEW_CODE), self.text(S_WITHOUT))
        self.phase, signing = 'retry', self.phase == 'signing'
        if signing:
            self.refocus()

    def refocus(self):
        """The buttons were hidden while signing in: focus the first one again. setFocusId is a thread message of
        Kodi's window manager (safe from this thread); the button shows a frame after its label is set."""
        import xbmc
        for _ in range(20):
            xbmc.sleep(100)
            try:
                self.setFocusId(B1)
            except Exception:
                pass
            if xbmc.getCondVisibility('Control.HasFocus({})'.format(B1)):
                break

    def signing(self, percent):
        if self.phase != 'signing':
            self.phase = 'signing'
            self.clear_code()
            self.buttons()                               # nothing to press while the switch runs
        message = self.text(S_SIGNING)
        self.status('{} {} %'.format(message, int(percent)) if percent else message, 'busy')

    def paired(self, user):
        from wcs.account import ui as account_ui
        parts = account_ui.merge_offer()
        self.status(self.text(S_SIGNED_IN, user.get('name', '')), 'ok')
        if parts:                                        # S28: this Kodi has data of its own
            self.setProperty('ob.title', self.text(S_MERGE_TITLE))
            self.setProperty('ob.text', self.text(S_MERGE_TEXT, parts))
            self.buttons(self.text(S_MERGE), self.text(S_ACCOUNT_ONLY))
            self.phase = 'merge'
        else:
            self.buttons(self.text(S_CONTINUE))
            self.phase = 'signed'
        self.refocus()
