# -*- coding: utf-8 -*-
"""Feedback of Pro tebe (docs/plan/pro-tebe/040): rate a title (Líbí se mi / Nelíbí se mi / Nezajímá mě) from the
context menu, and the first-run pick of favourites. Both write store.feedback and rebuild the snapshot at once, so the
page reacts while the user is still looking at it (a rebuild from the cache takes about a second).
"""
import xbmc
import xbmcaddon
import xbmcgui

ADDON_ID = 'plugin.video.milionar'
S_RATE, S_LIKE, S_DISLIKE, S_HIDE, S_CLEAR, S_THANKS = 35331, 35332, 35333, 35334, 35335, 35336
S_PICK_CARD, S_PICK_HEADING, S_PICK_DONE = 35337, 35338, 35339
FALLBACK = {35331: 'Hodnotit…', 35332: 'Líbí se mi', 35333: 'Nelíbí se mi', 35334: 'Nezajímá mě',
            35335: 'Zrušit hodnocení', 35336: 'Díky, doporučení se upraví', 35337: 'Vyber, co máš rád',
            35338: 'Vyber filmy a seriály, které máš rád', 35339: 'Díky, doporučení jsou podle tebe',
            35340: 'Zaškrtni filmy a seriály, které máš rád, a Pro tebe se hned přepočítá podle tvého vkusu.',
            35341: 'První krok · 1 minuta', 35342: 'Tvůj vkus', 35343: 'Čím víc vybereš, tím přesnější doporučení'}
CHOICES = (('like', S_LIKE), ('dislike', S_DISLIKE), ('hide', S_HIDE))
PICK_COUNT = 40
POSTER = 'https://image.tmdb.org/t/p/w342'


def text(string_id):
    return xbmcaddon.Addon(ADDON_ID).getLocalizedString(string_id) or FALLBACK.get(string_id, '')


def heading():
    from wcs.foryou.widgets import S_SECTION, _text
    return _text(S_SECTION)


def media_of(kind):
    """Context kinds (movie / tv / season / episode) -> the title the feedback belongs to."""
    return 'movie' if kind == 'movie' else 'tv'


def _rebuild():
    from wcs.foryou import service
    return service.build_now('feedback')


def rate(params):
    """Plugin action `foryou_rate&type=&tmdb=`: a select dialog with the three answers (+ clear when rated)."""
    from wcs.library2 import store
    media, tmdb_id = media_of(params.get('type', 'movie')), int(params['tmdb'])
    current = (store.get_feedback().get((media, tmdb_id)) or (None,))[0]
    options = list(CHOICES) + ([(None, S_CLEAR)] if current in ('like', 'dislike', 'hide') else [])
    labels = [text(string_id) for _value, string_id in options]
    preselect = next((i for i, (value, _s) in enumerate(options) if value == current), -1)
    title = params.get('title') or text(S_RATE).rstrip('…')
    choice = xbmcgui.Dialog().select(title, labels, preselect=preselect)
    if choice < 0:
        return
    value = options[choice][0]
    store.set_feedback(media, tmdb_id, value)
    xbmc.log('[Milionář ProTebe] feedback {} {}:{}'.format(value or 'cleared', media, tmdb_id), xbmc.LOGINFO)
    xbmcgui.Dialog().notification(heading(), text(S_THANKS), xbmcgui.NOTIFICATION_INFO, 2500, False)
    _rebuild()


def pick_candidates():
    """Well-known titles to choose from: the best-rated and the most popular films and series (TMDb, cached)."""
    from wcs.foryou import api
    lists = api.parallel([lambda p=p: api.results(*p) for p in (
        ('movie/top_rated', {}), ('movie/popular', {}), ('tv/top_rated', {}), ('tv/popular', {}),
        ('movie/top_rated', {'page': 2}), ('tv/top_rated', {'page': 2}))])
    seen, out = set(), []
    media_of_list = ('movie', 'movie', 'tv', 'tv', 'movie', 'tv')
    # interleave the lists so films and series alternate in the dialog
    for row in range(40):
        for media, items in zip(media_of_list, lists):
            if row < len(items or []):
                item = items[row]
                key = (media, int(item['id']))
                if key in seen or not item.get('poster_path') or (item.get('original_language') not in
                                                                  ('en', 'cs', 'sk', 'fr', 'de', 'es', 'it')):
                    continue
                seen.add(key)
                out.append((media, item))
    return out[:PICK_COUNT]


def pick(params=None):
    """Plugin action `foryou_pick`: the first-run choice of favourites (a multi-select with posters)."""
    from wcs.library2 import store
    candidates = pick_candidates()
    if not candidates:
        xbmcgui.Dialog().notification(heading(), text(35330) or 'Doporučení se teď nepodařilo připravit',
                                      xbmcgui.NOTIFICATION_WARNING, 3000, False)
        return
    already = {k for k, (v, _at) in store.get_feedback().items() if v == 'pick'}
    items, preselect = [], []
    for index, (media, data) in enumerate(candidates):
        title = data.get('title') or data.get('name') or ''
        year = (data.get('release_date') or data.get('first_air_date') or '')[:4]
        item = xbmcgui.ListItem(label=title, label2=year)
        item.setArt({'thumb': POSTER + data['poster_path'], 'icon': POSTER + data['poster_path']})
        items.append(item)
        if (media, int(data['id'])) in already:
            preselect.append(index)
    chosen = xbmcgui.Dialog().multiselect(text(S_PICK_HEADING), items, preselect=preselect, useDetails=True)
    if chosen is None:
        return
    chosen = set(chosen)
    for index, (media, data) in enumerate(candidates):
        key = (media, int(data['id']))
        if index in chosen and key not in already:
            store.set_feedback(media, key[1], 'pick')
        elif index not in chosen and key in already:
            store.set_feedback(media, key[1], None)
    xbmcgui.Dialog().notification(heading(), text(S_PICK_DONE), xbmcgui.NOTIFICATION_INFO, 2500, False)
    _rebuild()


def run(params):
    action = params.get('action', '')
    if action == 'foryou_rate':
        rate(params)
    elif action == 'foryou_pick':
        pick(params)
