# -*- coding: utf-8 -*-
"""Classic listings and their movable Home action rows; no catalogue/search logic here."""
from urllib.parse import urlencode

import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin

from wcs.library2 import urls

BASE = 'plugin://plugin.video.milionar/'
ROWS = {'home_movies_actions': 'my_movies', 'home_series_actions': 'my_series', 'home_vinyl_actions': 'vinyl'}
ROW_FOR = {sec: row for row, sec in ROWS.items()}
FLAG = 'MilionarNavigationV1'
S_CLASSIC = 32754


def command(sec, op='browse'):
    if sec == 'vinyl':
        return 'ActivateWindow(Music,{}?action=vinyl_browse,return)'.format(BASE)
    kind = 'movies' if sec == 'my_movies' else 'series'
    if op == 'add':
        return 'RunPlugin({})'.format(urls.add_url(kind))
    path = BASE + '?action=mlist&kind={}&skin=1'.format(kind)
    return 'ActivateWindow(Videos,{},return)'.format(path)


def run(params):
    sec = params.get('sec', '')
    if sec in ROW_FOR:
        xbmc.executebuiltin(command(sec, params.get('op', 'browse')))


def catalog(row):
    return ('browse',) if ROWS[row] == 'vinyl' else ('add', 'browse')


def label(row, op):
    return xbmcaddon.Addon('plugin.video.milionar').getLocalizedString(
        S_CLASSIC if op == 'browse' else 31118 if ROWS[row] == 'my_movies' else 31035)


def actions(row):
    return {op: (label(row, op), command(ROWS[row], op)) for op in catalog(row)}


def items(row, params):
    from wcs.skin import context
    sec = ROWS[row]
    available = actions(row)
    result = []
    for op, (title, builtin) in available.items():
        icon = 'DefaultAddSource.png' if op == 'add' else 'DefaultFolder.png'
        query = urlencode({'action': 'skin_classic', 'sec': sec, 'op': op})
        path = BASE + '?' + urlencode({'action': 'skin_run', 'run': query})
        item = xbmcgui.ListItem(label=title, path=path, offscreen=True)
        item.setArt({'icon': icon, 'thumb': icon, 'poster': icon})
        item.setProperty('IsPlayable', 'true')
        item.setProperty('milionar.type', 'action')
        data = {'type': 'action', 'title': title, 'extras': context.encode(available)}
        item.setProperty('milionar.ctxdata', context.pack(data))
        path, item, folder = context.attach(path, item, False, context.origin(params), row, hero=False)
        item.setProperty('milionar.exec', builtin)
        result.append((path, item, folder))
    return result


def widget(handle, row, params):
    result = items(row, params)
    xbmcplugin.addDirectoryItems(handle, result, len(result))
    xbmcplugin.endOfDirectory(handle, succeeded=True, cacheToDisc=False)


def migrate():
    """Append once without replacing widgets, UIDs, menus or hero layouts."""
    from wcs.skin import slots
    for sec, row in ROW_FOR.items():
        widgets = [slots.current(sec, n) for n in range(1, slots.SLOTS + 1)]
        if any(w['type'] == row for w in widgets):
            continue
        last = max((n for n, w in enumerate(widgets, 1) if w['type'] and w['type'] != 'off'), default=0)
        if last < slots.SLOTS:
            slots.write_slot(sec, last + 1, *slots.default_for(row, sec))
    xbmc.executebuiltin('Skin.SetBool({})'.format(FLAG), True)
    slots.reload_skin()


def repair_titles():
    """Fill headers created before the new addon translations were loaded; preserve configured widgets."""
    from wcs.skin import slots
    title = slots._text(32755)
    if not title:
        return False
    for sec, row in ROW_FOR.items():
        for n in range(1, slots.SLOTS + 1):
            prefix = 'mil.{}.{}.'.format(sec, n)
            if (xbmc.getInfoLabel('Skin.String({}type)'.format(prefix)) == row and
                    not xbmc.getInfoLabel('Skin.String({}title)'.format(prefix))):
                slots._set(prefix + 'title', title)
    xbmc.executebuiltin('Skin.SetBool(MilionarNavigationTitlesV1)', True)
    return True
