# -*- coding: utf-8 -*-
"""Rows of the genre browser: the genre cards of Pro tebe (fy_genres) and the rows of the genre page (gn_*).

Like every Home row they never call the network: the genre row reads the cached TMDb genre lists and the Pro tebe
snapshot, the genre page's rows read the view its controller prepared (wcs/genres/page.py, `meta` key
genre:view:<token>). Cards are the library builders (wcs/library2/rows.py) through the Pro tebe card
(wcs/foryou/widgets._card), so the hero, clicks and context menus behave as everywhere else.
"""
import time
from urllib.parse import quote, urlencode

import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin

from wcs.genres import catalog, contract
from wcs.skin import hero

ADDON_ID = 'plugin.video.milionar'
BASE = 'plugin://plugin.video.milionar/'
VIEW_KEY = 'genre:view:{}'
GENRE_ICON = 'DefaultGenre.png'                       # the genre tiles of Filmy (wcs/library2/rows.genre_item)
# Estuary's own "more" chevron of the rows; Předchozí draws it mirrored (milionar.card.flip, gen_cinema CARD_POSTER)
NEXT_ICON = PREVIOUS_ICON = 'overlays/arrowright.png'
EMPTY_ICON = 'DefaultIconInfo.png'
S_NEXT, S_PREVIOUS, S_PAGE, S_EMPTY, S_EMPTY_HINT = 35575, 35576, 35577, 35578, 35579
S_OPEN, S_GENRE, S_GENRE_PLOT = 32634, 35732, 35733
S_FOR_YOU, S_EVERYTHING, S_PAGE_NEXT, S_PAGE_PREVIOUS = 35300, 35745, 35743, 35744
EXAMPLES = 6                                          # titles a genre card's hero names at most


def text(string_id):
    return xbmcaddon.Addon(ADDON_ID).getLocalizedString(string_id)


def genre_name(key, extra=None):
    if key in catalog.GENRES:
        return text(catalog.GENRES[key][0])
    return ((extra or {}).get(key) or {}).get('name') or key


def builtin(action, **params):
    return 'RunPlugin({}?{})'.format(BASE.rstrip('/'), urlencode(dict(params, action=action)))


def _action_item(label, command, icon, label2='', card_icon=False, flip=False, kicker='', plot='', backdrop='', open_label='',
                 badge='', now='', second=None):
    """A card that runs `command` (the Pro tebe pick card's pattern: a playable skin_run path, the builtin in exec).
    `card_icon`: a poster card draws the icon over its middle instead of a poster (gen_cinema CARD_POSTER).
    The hero names the card itself (hero.tile): `kicker`, `plot`, `backdrop`, `badge`, `now`, its button `open_label`
    and `second`."""
    path = '{}?action=skin_run&run={}'.format(BASE, quote(command[len('RunPlugin({}?'.format(BASE.rstrip('/'))):-1], safe=''))
    item = xbmcgui.ListItem(label=label, label2=label2, path=path, offscreen=True)
    item.setArt({'icon': icon, 'thumb': icon})
    item.setProperty('milionar.exec', command)
    item.setProperty('IsPlayable', 'true')
    hero.tile(item, label, kicker or label2, plot, backdrop, open_label or label, command, badge, now, second)
    if card_icon:
        item.setProperty('milionar.card.icon', icon)
        item.setProperty('milionar.card.flip', '1' if flip else '')
    return path, item, False


# --------------------------------------------------------------------------- Pro tebe: the genre cards

def sources_of(snapshot):
    """The profile's genre weights per source; an older snapshot only knows its four taste genres."""
    if (snapshot or {}).get('genre_sources'):
        return snapshot['genre_sources']
    return {'watched': {int(g): 1.0 for g in (snapshot or {}).get('taste') or []}}


def genre_order(mode, values, snapshot, extra=None):
    """(keys, mine) of the genre row of Pro tebe in `mode` ('' / movie / tv) with the widget's options."""
    weights = {'library': values['w_library'], 'watched': values['w_watched'], 'like': values['w_like'],
               'dislike': values['w_dislike']}
    from wcs.foryou import signals
    keys = catalog.listed(mode, values['tv_only'], extra)
    return catalog.ordered(keys, sources_of(snapshot), weights, values['threshold'], signals.chosen_genres())


def showcase(keys, snapshot, mode):
    """{genre key: (backdrop URL, titles)} from the Pro tebe snapshot, best titles first and each backdrop for one genre
    only: the hero of a genre card pictures the genre and names some of its titles."""
    from wcs.foryou import features
    medias = {'movie': ('movie',), 'tv': ('tv',)}.get(mode, ('movie', 'tv'))
    titles = sorted(((snapshot or {}).get('items') or {}).values(), key=lambda t: -float(t.get('score') or 0))
    titles = [t for t in titles if t.get('media') in medias]
    out, used = {}, set()
    for key in keys:
        entry = catalog.GENRES.get(key)
        ids = entry[1] + entry[2] if entry else (int(key[len(catalog.EXTRA):]),) if key[len(catalog.EXTRA):].isdigit() else ()
        wanted = set(features.folded_genres(ids))
        fitting = [t for t in titles if wanted & set(features.folded_genres(t.get('genres') or []))]
        pictured = [t for t in fitting if t.get('backdrop')]
        title = next((t for t in pictured if t['backdrop'] not in used), pictured[0] if pictured else None)
        if title:
            used.add(title['backdrop'])
        out[key] = (hero.fanart(title) if title else '', [t['title'] for t in fitting if t.get('title')][:EXAMPLES])
    return out


def genre_cards(params):
    from wcs.foryou import engine, mode as modes
    from wcs.genres import options, tmdb
    sec, slot = params.get('sec', 'foryou'), params.get('slot', '')
    values = options.values(contract.FY_ROW, xbmc.getInfoLabel('Skin.String(mil.{}.{}.opts)'.format(sec, slot)) if slot else '')
    mode = params.get('mode') if params.get('mode') in ('movie', 'tv') else ''
    extra = tmdb.Source().extras(cached_only=True)
    snapshot = engine.load()
    keys, mine = genre_order(mode, values, snapshot, extra)
    shown = showcase(keys, snapshot, mode)
    media = modes.name(mode) if mode else text(S_EVERYTHING)
    second = (modes.ACTION, modes.label(mode), modes.builtin())
    items = []
    for key in keys:
        name = genre_name(key, extra)
        backdrop, titles = shown.get(key, ('', []))
        path, item, folder = _action_item(name, builtin('genre_open', genre=key, mode=mode), GENRE_ICON,
                                          kicker=text(S_FOR_YOU), plot=hero.examples(text(S_GENRE_PLOT).format(name), titles),
                                          backdrop=backdrop, open_label=text(S_OPEN), badge=text(S_GENRE), now=media,
                                          second=second)
        item.getVideoInfoTag().setTitle(name)
        item.setProperty('milionar.genre.key', key)
        item.setProperty('milionar.genre.mine', '1' if key in mine else '')
        items.append((path, item, folder))
    return items


# --------------------------------------------------------------------------- the rows of the genre page

def load_view(token):
    from wcs.library2 import meta
    data, _stale = meta.get(VIEW_KEY.format(token)) if token else (None, True)
    return data if isinstance(data, dict) else None


def _cards(entries, names, click):
    """ListItems of TMDb cards (wcs/foryou/features.card) through the library builders."""
    from wcs.foryou import widgets as foryou_widgets
    from wcs.library2 import rows
    descriptors = []
    for entry in entries:
        named = dict(entry, genre_names=[names.get(str(g)) for g in entry.get('genres') or [] if names.get(str(g))])
        card = foryou_widgets._card(named)
        descriptors.append({'kind': card['kind'], 'card': card, 'click': click, 'landscape': False,
                            'episode': None, 'episode_kind': ''})
    items = rows._render(rows._prepare(descriptors, rows.Data()))
    for entry, (_path, item, _folder) in zip(entries, items):
        if entry.get('star'):
            item.setProperty('milionar.genre.star', entry['star'])        # the rating badge of a listing card
    return items


def view_rows(row, view, slot, click):
    """The items of slot `slot` of a prepared view."""
    entries = (view.get('rows') or {}).get(str(slot))
    if entries is None:
        return []
    items = _cards(entries, view.get('names') or {}, click)
    if row != contract.LIST:
        return items
    listing = view.get('list') or {}
    picture = next((hero.fanart(entry) for entry in entries if entry.get('backdrop')), '')
    line = {'badge': text(S_GENRE), 'now': xbmcgui.Window(10000).getProperty(contract.PREFIX + 'name')}
    if listing.get('page', 1) > 1:
        items.insert(0, _action_item(text(S_PREVIOUS), builtin('genre_page', go='previous'), PREVIOUS_ICON,
                                     text(S_PAGE).format(listing['page'] - 1), True, flip=True, backdrop=picture,
                                     plot=text(S_PAGE_PREVIOUS), **line))
    if listing.get('more'):
        items.append(_action_item(text(S_NEXT), builtin('genre_page', go='next'), NEXT_ICON,
                                  text(S_PAGE).format(listing.get('page', 1) + 1), True, backdrop=picture,
                                  plot=text(S_PAGE_NEXT), **line))
    if not entries:
        items.append(_action_item(text(S_EMPTY), builtin('genre_filter', f='media'), EMPTY_ICON, text(S_EMPTY_HINT), True,
                                  plot=text(S_EMPTY_HINT), open_label=text(S_OPEN), **line))
    return items


def build(row, params):
    from wcs.library2 import clicks
    if row == contract.FY_ROW:
        return genre_cards(params)
    view = load_view(params.get('g', ''))
    if not view:
        return []
    return view_rows(row, view, params.get('slot', ''), clicks.resolve(row, params.get('click') or ''))


def run(handle, params):
    started = time.perf_counter()
    row = params.get('row', '')
    items = []
    try:
        items = build(row, params)
    except Exception as exc:                              # a broken row must never break Home
        xbmc.log('[Milionář Žánry] row {} failed: {}: {}'.format(row, type(exc).__name__, exc), xbmc.LOGERROR)
    xbmcplugin.addDirectoryItems(handle, items, len(items))
    xbmcplugin.endOfDirectory(handle, succeeded=True, cacheToDisc=False)
    xbmc.log('[Milionář Žánry] widget_row {} -> {} items in {:.0f} ms'.format(
        row, len(items), (time.perf_counter() - started) * 1000), xbmc.LOGDEBUG)
