# -*- coding: utf-8 -*-
"""Vinyl stays off until the user switches it on in its section (docs/plan/onboarding/000-plan.md D22).

Until then nothing of Vinyl loads (wcs.skin.warm.hidden) and the section shows only its hero: what Vinyl is, with the
button that switches it on (D25). The hero reads the one card of the first row, which the skin keeps hidden and hands its
focus to the button (`milionar.hero.only`, gen_cinema.HERO_ONLY_SLOTS): the section is never empty and costs nothing. An installation that already
has Vinyl's data from an earlier version counts as switched on.
"""
import os
import threading

import xbmc
import xbmcaddon
import xbmcgui

ADDON_ID = 'plugin.video.milionar'
SETTING = 'vinyl_activated'
PROPERTY = 'milionar.vinyl.active'               # Window(Home): '1' when Vinyl is on (the service publishes it)
ACTION = 'RunPlugin(plugin://plugin.video.milionar/?action=vinyl_activate)'
CARD_PATH = 'plugin://plugin.video.milionar/?action=vinyl_activate'
CARD_ICON = 'DefaultMusicAlbums.png'
SIG = 'vinyl-activation'
S_KICKER, S_PLOT, S_BUTTON, S_LOADING, S_READY, S_FAILED = 35801, 35802, 35803, 35804, 35805, 35806
WAIT_S = 45
_running = threading.Lock()


def active():
    return xbmcgui.Window(10000).getProperty(PROPERTY) == '1'


def _has_data():
    from wcs.vinyl import client
    folder = os.path.dirname(client.cache_path('curator'))
    try:
        return any(name.startswith('vinyl_') for name in os.listdir(folder))
    except OSError:
        return False


def sync(addon):
    """Service: publish the switch. Vinyl's data from an earlier version switches it on once."""
    on = addon.getSetting(SETTING) == 'true'
    if not on and _has_data():
        addon.setSetting(SETTING, 'true')
        on = True
    home = xbmcgui.Window(10000)
    if on:
        home.setProperty(PROPERTY, '1')
    else:
        home.clearProperty(PROPERTY)
    return on


class _Card(object):
    """The few ListItem calls wcs.skin.hero makes, kept as the properties of a row file's card."""

    def __init__(self):
        self.props = {}

    def setProperty(self, key, value):
        self.props[key.lower()] = value

    def getProperty(self, key):
        return self.props.get(key.lower(), '')


def card(addon=None):
    """(label, properties, path) of the activation card."""
    from wcs.skin import hero
    addon = addon or xbmcaddon.Addon(ADDON_ID)
    item = _Card()
    hero.tile(item, 'Vinyl', addon.getLocalizedString(S_KICKER), addon.getLocalizedString(S_PLOT), '',
              addon.getLocalizedString(S_BUTTON), ACTION)
    item.setProperty('label2', addon.getLocalizedString(S_KICKER))
    item.setProperty('art.icon', CARD_ICON)
    item.setProperty('milionar.hero.only', '1')       # no card in the row, only the hero (D25)
    item.setProperty('milionar.exec', ACTION)
    item.setProperty('isplayable', 'true')
    return 'Vinyl', item.props, CARD_PATH


def show_card():
    """Service, while Vinyl is off: its first row holds the activation card (shown only as the hero), the others none."""
    from wcs.skin import journal, rowfiles
    from wcs.skin.hero_contract import slot_count
    name = rowfiles.row_name('vinyl', '1')
    rowfiles.publish(name, [card()], SIG, None, live=True, code=journal.stamp())
    journal._flag('vinyl', '1', rowfiles.ONE)
    journal._shown('vinyl', '1', 1, None)
    for slot in range(2, slot_count('vinyl') + 1):
        if rowfiles.head(rowfiles.row_name('vinyl', str(slot))):
            rowfiles.publish(rowfiles.row_name('vinyl', str(slot)), [], SIG, None, live=True, code=journal.stamp())
            journal._flag('vinyl', str(slot), rowfiles.NONE)


def activate():
    """The card's button: Vinyl's data first (a live progress), then its rows; the card stays until they have cards.
    Runs where the action runs (a thread of its own in the service, wcs/skin/commands.py; or the plugin's process)."""
    if not _running.acquire(blocking=False):
        return
    addon = xbmcaddon.Addon(ADDON_ID)
    progress = xbmcgui.DialogProgressBG()
    try:
        progress.create('Vinyl', addon.getLocalizedString(S_LOADING))
        addon.setSetting(SETTING, 'true')
        xbmcgui.Window(10000).setProperty(PROPERTY, '1')
        from wcs.skin import refresh, refresher
        from wcs.skin.hero_contract import slot_count
        from wcs.vinyl import widgets
        rows = sorted(refresher.active_rows() & refresh.VINYL_ROWS)
        sources = [row[len('vinyl_'):] for row in rows]
        progress.update(20)
        from wcs.vinyl import client
        widgets.refresh(sources=sources)
        ok = any(client.snapshot(source) for source in sources)
        if not ok:                                    # no data: the card stays, the user can try again
            addon.setSetting(SETTING, 'false')
            xbmcgui.Window(10000).clearProperty(PROPERTY)
            progress.update(100, message=addon.getLocalizedString(S_FAILED))
            xbmc.Monitor().waitForAbort(3)
            return
        progress.update(70)
        refresh.rebuild({('vinyl', slot) for slot in range(1, slot_count('vinyl') + 1)}, force=True)
        monitor = xbmc.Monitor()
        from wcs.skin import rowfiles
        for _ in range(WAIT_S * 4):
            head = rowfiles.head(rowfiles.row_name('vinyl', '1')) or {}
            if head.get('sig') != SIG:
                break
            if monitor.waitForAbort(0.25):
                return
        progress.update(100, message=addon.getLocalizedString(S_READY))
        monitor.waitForAbort(1.5)
    finally:
        progress.close()
        _running.release()
