# -*- coding: utf-8 -*-
"""Kodi screens of the account (docs/plan/milionar-account/040): the sign-in window with the QR code, the account item
(menu 1108 / settings), the sign-out, the key lock (S5) and the reset warning (S26).

The pairing runs in a background thread that only sets window properties (never touches a control); the switch itself
runs in that thread too and reports through the status property."""
import threading

import xbmc
import xbmcaddon
import xbmcgui

from wcs.account import client, state

XML = 'account/DialogMilionarAccount.xml'
OPEN = 'milionar.account.dialog'      # Window(Home): the account window is open (a skin reload waits, foryou/service.py)
B1, B2 = 11, 12
BACK = (xbmcgui.ACTION_NAV_BACK, xbmcgui.ACTION_PREVIOUS_MENU)
S_LABEL, S_SIGN_IN = 36000, 36001
S_KICKER, S_TITLE, S_TEXT, S_CLOSE, S_NEW_CODE = 36002, 36003, 36004, 36006, 36007
S_WAITING, S_SIGNING, S_SIGNED_IN, S_SIGNED_OUT, S_EXPIRED, S_OFFLINE, S_DENIED, S_UPGRADE = range(36008, 36016)
S_SIGNOUT_Q, S_SIGNOUT, S_ON_WEB, S_MANAGED, S_UNSENT, S_RESET_1, S_RESET_2, S_RESET_ALL = range(36016, 36024)
S_NOT_SIGNED, S_SIGNED_AS, S_WEB_HINT, S_STOP_PLAYBACK = 36028, 36029, 36030, 36034
S_MERGE_TITLE, S_MERGE_TEXT, S_MERGE, S_ACCOUNT_ONLY = 36038, 36039, 36040, 36041
S_COUNTS = (('movies', 36043), ('series', 36044), ('in_progress', 36045), ('watched', 36046), ('mytv', 36047), ('mycinema', 36048))


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


def text(string_id, *args):
    value = _addon().getLocalizedString(string_id)
    return value.format(*args) if args else value


def device_name():
    from wcs.account import pairing
    return pairing.device_name()


def merge_offer():
    """S28: the counts of this Kodi's own data as one line, or '' when there is nothing to merge."""
    from wcs.account import merge
    try:
        counts = merge.summary()
    except Exception as exc:
        client._log('merge summary failed: {}'.format(type(exc).__name__))
        return ''
    if not merge.has_data(counts):
        return ''
    return ' · '.join(text(string_id, counts[key]) for key, string_id in S_COUNTS if counts.get(key))


class PairWindow(xbmcgui.WindowXMLDialog):
    """Sign in: QR code + code; the phone approves on the web (S1). result: True = signed in."""

    def __init__(self, *args, **kwargs):
        self.offer_only = kwargs.pop('offer_only', False)     # signed in already: only the merge offer (S28)
        super(PairWindow, self).__init__(*args, **kwargs)
        self.result = self.offer_only
        self.merge = False                   # S28: the user chose to merge this Kodi's data into the account
        self.offering = False
        self.answered = False                # the user closed the window (a skin reload closes it without an answer)
        from wcs.account import pairing
        self.pairing = pairing.Pairing(self)

    def onInit(self):
        if self.offer_only:
            self.setProperty('ac.kicker', text(S_KICKER))
            self.status(text(S_SIGNED_IN, _addon().getSetting(state.NAME)), 'ok')
            threading.Thread(target=lambda: self.offer() or self.close(), name='milionar-account-offer', daemon=True).start()
            return
        self.setProperty('ac.kicker', text(S_KICKER))
        self.setProperty('ac.title', text(S_TITLE))
        self.setProperty('ac.text', text(S_TEXT))
        self.setProperty('ac.b1', text(S_CLOSE))
        self.start()
        self.setFocusId(B1)

    def status(self, message, kind=''):
        self.setProperty('ac.status', message)
        self.setProperty('ac.status.kind', kind)

    def start(self):
        self.setProperty('ac.b2', '')
        self.pairing.start()

    # the pairing's view (its thread: properties only)
    def waiting(self):
        self.status(text(S_WAITING), 'busy')

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

    def expired(self):
        self.setProperty('ac.qr', '')
        self.setProperty('ac.code', '')
        self.status(text(S_EXPIRED), 'error')
        self.setProperty('ac.b2', text(S_NEW_CODE))

    def offline(self, upgrade):
        self.status(text(S_UPGRADE if upgrade else S_OFFLINE), 'error')
        self.setProperty('ac.b2', text(S_NEW_CODE))

    def signing(self, percent):
        self.setProperty('ac.b1', '')
        self.setProperty('ac.qr', '')
        self.status('{} {} %'.format(text(S_SIGNING), int(percent)) if percent else text(S_SIGNING), 'busy')

    def paired(self, user):
        self.status(text(S_SIGNED_IN, user.get('name', '')), 'ok')
        self.result = True
        if self.offer():
            return
        xbmc.sleep(900)
        self.close()

    def failed(self):
        self.status(text(S_OFFLINE), 'error')
        self.setProperty('ac.b1', text(S_CLOSE))
        self.setProperty('ac.b2', text(S_NEW_CODE))

    def offer(self):
        """S28: this Kodi has data of its own — merge it into the account, or use only the account."""
        parts = merge_offer()
        if not parts:
            return False
        self.setProperty('ac.title', text(S_MERGE_TITLE))
        self.setProperty('ac.text', text(S_MERGE_TEXT, parts))
        self.setProperty('ac.b1', text(S_MERGE))
        self.setProperty('ac.b2', text(S_ACCOUNT_ONLY))
        self.offering = True
        # on this window itself (the SetFocus builtin goes to the topmost dialog: the corner progress); the button shows a
        # frame after its label is set
        for _ in range(20):
            xbmc.sleep(100)
            try:
                self.setFocusId(B1)
            except Exception:
                pass
            if xbmc.getCondVisibility('Control.HasFocus({})'.format(B1)) or self.pairing.closing.is_set():
                break
        return True

    def onClick(self, control):
        if self.offering and control in (B1, B2):
            self.merge = control == B1
            self.answered = True
            self.pairing.stop()
            self.close()
            return
        if control == B1 and self.getProperty('ac.b1'):
            self.pairing.stop()
            self.close()
        elif control == B2 and self.getProperty('ac.b2'):
            self.start()

    def onAction(self, action):
        if action.getId() in BACK and self.getProperty('ac.b1'):
            self.answered = True
            self.pairing.stop()
            self.close()


def pair():
    """Open the sign-in window; True when the device is now signed in."""
    if xbmc.getCondVisibility('Player.HasMedia'):
        xbmcgui.Dialog().notification('Milionář', text(S_STOP_PLAYBACK), xbmcgui.NOTIFICATION_INFO, 4000)
        return False
    home = xbmcgui.Window(10000)
    home.setProperty(OPEN, '1')
    try:
        return _pair()
    finally:
        home.clearProperty(OPEN)


def _pair():
    window = PairWindow(XML, _addon().getAddonInfo('path'), 'Default', '1080i')
    window.doModal()
    result, chosen, unanswered = window.result, window.merge, window.offering and not window.answered
    del window
    for _attempt in range(3):
        if not (result and unanswered):
            break
        # a skin reload right after the sign-in (Pro tebe's first rows) closed the offer: it comes back
        xbmc.sleep(1500)
        window = PairWindow(XML, _addon().getAddonInfo('path'), 'Default', '1080i', offer_only=True)
        window.doModal()
        chosen, unanswered = window.merge, window.offering and not window.answered
        del window
    if result and chosen:
        _merge()
    return result


def _merge():
    """Queue the merge (wcs/account/merge.py); the service shows its progress and the push sends it."""
    from wcs.account import merge, switch
    try:
        added = merge.enqueue()
        client._log('merge queued: {} ops'.format(added))
        switch.notify('account_merge')
    except Exception as exc:
        client._log('merge failed: {}: {}'.format(type(exc).__name__, exc))


def account_menu():
    """The account item (skin menu 1108, settings): sign in, or the account with its sign-out (S19, S24)."""
    if not state.signed_in():
        pair()
        return
    addon = _addon()
    name, email = addon.getSetting(state.NAME), addon.getSetting(state.EMAIL)
    choice = xbmcgui.Dialog().select(text(S_SIGNED_AS, name, email), [text(S_SIGNOUT), text(S_CLOSE)])
    if choice == 0:
        signout_confirm()


def signout_confirm():
    addon = _addon()
    name = addon.getSetting(state.NAME)
    if not xbmcgui.Dialog().yesno(text(S_SIGNOUT), text(S_SIGNOUT_Q, name)):
        return
    from wcs.account import switch
    switch.notify('account_signout')                     # the service signs out (its threads)


def ask_unsent(count):
    """S20: some changes could not be sent."""
    return xbmcgui.Dialog().yesno(text(S_SIGNOUT), text(S_UNSENT, count))


def keys_locked():
    """S5: signed in, keys and logins are managed on the web; True = the caller must not open its key window."""
    if not state.signed_in():
        return False
    xbmcgui.Dialog().ok('Milionář', text(S_ON_WEB, client.server() + 'settings/accounts'))
    return True


def reset_confirmed():
    """S26: signed in, the reset deletes the account's history everywhere — two warnings, Cancel focused."""
    name = _addon().getSetting(state.NAME)
    dialog = xbmcgui.Dialog()
    if not dialog.yesno(text(S_RESET_ALL), text(S_RESET_1, name), defaultbutton=xbmcgui.DLG_YESNO_NO_BTN):
        return False
    return dialog.yesno(text(S_RESET_ALL), text(S_RESET_2, name), yeslabel=text(S_RESET_ALL),
                        defaultbutton=xbmcgui.DLG_YESNO_NO_BTN)
