# -*- coding: utf-8 -*-
"""The genre page on Home (docs/plan/genre-browser/020): opened from a genre card of Pro tebe, a pinned hero with the
filters as hero buttons (Typ, Rok, Země, Řazení, Výběr, Zpět) and the rows of the widget manager's section `genre`.

This controller is the only part that talks to TMDb and Webshare. It prepares a view (the listing page and every side
row), stores it in `meta` (genre:view:<token>) and gives each row the token once its cards are there (token.<slot>);
the rows (wcs/genres/widgets.py) only read it. The page opens at once (wcs/skin/pages.Loading): a view the cache has shows whole, anything else fills row
by row while Kodi's background progress names the step; the previous view never shows meanwhile.
Window(Home) properties milionar.genre.* carry the presentation and the navigation (never credentials).
"""
import hashlib
import json
import threading

import xbmc
import xbmcaddon
import xbmcgui

from wcs.genres import catalog, contract, cursor, rows, settings, widgets
from wcs.quality import rules as quality, settings as quality_settings
from wcs.skin import pages

PREFIX = contract.PREFIX
ARROW = ' [COLOR C0FFFFFF]▼[/COLOR]'                 # the button opens a menu (wcs/foryou/mode.py)
MEDIA = (('movie', 342), ('tv', 20343), ('', 35537))  # Filmy, Seriály (Kodi's strings), Oboje
SORTS = (('date', 35557), ('rating', 35558), ('popularity', 35559))
ORIGINS = tuple(quality_settings.ORIGIN_LABELS.items())         # Západní, Celý svět, Anime, Asie
S_MEDIA, S_YEAR, S_COUNTRY, S_SORT, S_ORIGIN = 35536, 35538, 35554, 35556, 35620
S_ALL_YEARS, S_ALL_COUNTRIES, S_ALL, S_MORE, S_BACK = 35587, 35588, 593, 32420, 32682
S_HEADING, S_LOAD_LIST, S_LOAD_ROWS, S_CHECK, S_FAILED, S_PAGE = 35580, 35581, 35582, 35583, 35584, 35577
S_SERVICES = 35634
EMPTY_RETRIES = 3                  # a page the filter emptied looks a little further before it says "nothing found"
FORYOU_CHECK = 40                  # Doporučeno pro tebe: titles asked on Webshare at most (cached 3-7 days)


def text(string_id):
    if string_id < 30000:
        return xbmc.getLocalizedString(string_id)
    return xbmcaddon.Addon('plugin.video.milionar').getLocalizedString(string_id)


def _home():
    return xbmcgui.Window(10000)


def _get(name):
    return _home().getProperty(PREFIX + name)


def _set(name, value):
    _home().setProperty(PREFIX + name, str(value))


def _state():
    raw = _get('state')
    return json.loads(raw) if raw else None


def default_filters(mode=''):
    """A page opens with the global Původ (Kvalita návrhů); choosing another one is for this page only."""
    return {'media': mode if mode in ('movie', 'tv') else '', 'year': '', 'country': '', 'sort': 'date',
            'origin': quality_settings.values()['origin']}


# --------------------------------------------------------------------------- labels

def _name(pairs, value):
    return text(dict(pairs).get(value, pairs[0][1]))


def country_name(iso, source=None):
    if not iso:
        return text(S_ALL)
    names = dict((source or settings.source()).countries())
    return names.get(iso, iso)


def labels(state, source=None):
    filters = state['filters']
    return {'media': text(S_MEDIA).format(_name(MEDIA, filters['media'])) + ARROW,
            'year': text(S_YEAR).format(filters['year'] or text(S_ALL)) + ARROW,
            'country': text(S_COUNTRY).format(country_name(filters['country'], source)) + ARROW,
            'sort': text(S_SORT).format(_name(SORTS, filters['sort'])) + ARROW,
            'origin': text(S_ORIGIN).format(_name(ORIGINS, filters.get('origin', quality.DEFAULT))) + ARROW,
            'back': text(S_BACK)}


def kicker(state, source=None):
    """'FILMY · 1985 · ČESKO' over the genre's name."""
    from wcs.skin import hero
    filters = state['filters']
    parts = [_name(MEDIA, filters['media']), filters['year'] or text(S_ALL_YEARS),
             country_name(filters['country'], source) if filters['country'] else text(S_ALL_COUNTRIES)]
    return hero.track(' · '.join(parts).upper())


# --------------------------------------------------------------------------- the view

def _known():
    """Titles the household knows (library lists, watched, in progress, rated, Pro tebe): never filtered away."""
    try:
        from wcs.foryou import signals
        _seeds, exclude = signals.load()
        return set('{}:{}'.format(m, i) for m, i in exclude)
    except Exception as exc:
        xbmc.log('[Milionář Žánry] library state: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
        return set()


def _signature(state):
    """What the view depends on: genre, filters, the page's cursor, the slots and their options, the day."""
    from datetime import date
    slots = [(n, row, xbmc.getInfoLabel('Skin.String(mil.{}.{}.opts)'.format(contract.SEC, n)))
             for n, row in settings.slot_rows()]
    raw = json.dumps([state['key'], state['filters'], state.get('cursor'), slots, date.today().isoformat()], sort_keys=True)
    return hashlib.sha1(raw.encode('utf-8')).hexdigest()[:16]


def listing(source, state, values, known, extra=None, max_requests=None):
    """(entries, next cursor, info) of the listing page `state['cursor']` points at."""
    from wcs.foryou import api, features as F
    filters = dict(state['filters'], rating_votes=values['rating_votes'])
    filters.setdefault('origin', quality.DEFAULT)
    queries = source.queries(state['key'], filters, extra, values)
    if not queries:
        return [], None, {'end': True, 'failed': False}

    def accept(name, item):
        media, _slash, rule = name.partition('/')
        return quality.keep(rule, item, values, F.key(media, item['id']) in known)
    position = state.get('cursor')
    found, info = [], {'end': True, 'failed': False}
    for _attempt in range(EMPTY_RETRIES):
        items, position, info = cursor.page(source.fetch, queries, filters['sort'], position,
                                            max_requests=max(max_requests or settings.requests_per_page(), len(queries)),
                                            accept=accept, parallel=api.parallel)
        found.extend(items)
        if found or info['end'] or info['failed']:
            break
    entries = []
    for media, item in found:
        entry = F.card(item, media)
        if quality.star(entry, values['star']):
            entry['star'] = '★ {:.1f}'.format(entry['rating'])
        entries.append(entry)
    return entries, position, info


def _foryou(source, state, ranked, snapshot, medias, extra, progress):
    """Doporučeno pro tebe: the Pro tebe titles of the genre, then the ranked TMDb ones, only what Webshare plays."""
    from wcs.foryou import availability, features as F
    exclude = _known() - set(((snapshot or {}).get('items') or {}))
    first = rows.snapshot_cards(snapshot, catalog.taste_ids(state['key']) or (), medias, state['filters'])
    pool, seen = [], set()
    for card in first + ranked:
        key = F.key(card['media'], card['id'])
        if key in seen or key in exclude:
            continue
        seen.add(key)
        pool.append(card)
    pool = pool[:FORYOU_CHECK]
    try:
        found = availability.check_many([dict(c) for c in pool], budget=FORYOU_CHECK,
                                        progress=lambda done, total: progress(done, total))
    except availability.Unavailable as exc:          # no Webshare account: unverified, like Pro tebe
        xbmc.log('[Milionář Žánry] Webshare check off: {}'.format(exc), xbmc.LOGINFO)
        return pool
    return [c for c in pool if (found.get(F.key(c['media'], c['id'])) or {}).get('status') == 'ok']


def _ignore(_view, _slot):
    pass


def compute(state, progress, ready=_ignore):
    """The whole view of `state` (rows by slot) and the cursor after the listing page; `ready(view, slot)` is told
    as soon as a row has its cards (the listing first), so the page fills while the rest loads."""
    from wcs.foryou import api, engine, features as F
    source = settings.source()
    progress.update(2, text(S_LOAD_LIST))
    extra = source.extras(cached_only=False)
    slots = settings.slot_rows()
    values = settings.widget_options(contract.LIST, contract.SEC)
    known = _known()
    snapshot = engine.load()
    view = {'rows': {}, 'names': {str(k): v for k, v in api.genre_names().items()}, 'list': {}}
    next_cursor, failed = None, False
    list_slots = [n for n, row in slots if row == contract.LIST]
    if list_slots:
        entries, next_cursor, info = listing(source, state, values, known, extra)
        failed = info.get('failed') and not entries
        progress.update(20, text(S_SERVICES))
        _services(entries)
        view['rows'][str(list_slots[0])] = entries
        view['list_slot'] = list_slots[0]                 # shown also when empty: its "Nic nenalezeno" card
        view['list'] = {'page': state['page'], 'more': not info.get('end'), 'count': len(entries)}
        if not failed:
            ready(view, list_slots[0])
    side = [(n, row) for n, row in slots if row != contract.LIST and row in contract.ROW_TYPES
            and fits_year(row, state['filters'].get('year'))]
    medias = catalog.media_of(state['key'], state['filters']['media'], extra)
    taste = rows.taste_of(widgets.sources_of(snapshot))
    used = set()
    for index, (n, row) in enumerate(side):
        start, end = 30 + 60.0 * index / len(side), 30 + 60.0 * (index + 1) / len(side)
        progress.update(start, text(S_LOAD_ROWS).format(index + 1, len(side)))
        kind = 'gn_decade' if row.startswith('gn_decade_') else row
        decade = contract.decade_years(row) if kind == 'gn_decade' else None
        calls = source.row_queries(kind, state['key'], state['filters'], extra, decade)
        answers = api.parallel([lambda c=c: source.fetch(c[0], c[1]) for c in calls])
        answered = [(c[0], a) for c, a in zip(calls, answers)]
        classes = _classes(answered)
        ranked = [c for c in rows.rank(row, answered, taste, snapshot, exclude=used, classes=classes)
                  if quality.judge(c, values, classes.get(F.key(c['media'], c['id'])) or 0,
                                   state['filters'].get('origin'))]                # the page's Původ in every row
        if row == contract.FORYOU:
            ranked = _foryou(source, state, ranked, snapshot, medias, extra,
                             lambda done, total: progress.update(start + (end - start) * done / max(total, 1),
                                                                 text(S_CHECK).format(done, total)))
            ranked = [c for c in ranked if F.key(c['media'], c['id']) not in used]
        chosen = ranked[:rows.ROW_SIZE]
        _services(chosen)
        used.update(F.key(c['media'], c['id']) for c in chosen)
        view['rows'][str(n)] = chosen
        ready(view, n)
    progress.update(100, text(S_LOAD_LIST))
    return view, next_cursor, failed


def _classes(answered):
    """{'movie:603': service class} of the titles in TMDb answers whose services the cache knows (no network)."""
    from wcs.services import catalog as services, store
    pairs = [(media, data['id']) for media, results in answered for data in results or [] if data.get('id')]
    found, _missing = store.lookup(pairs)
    return {'{}:{}'.format(*store.parse_key(k)): services.class_of(v) for k, v in found.items()}


def _services(entries):
    """The CZ services of the cards a view shows, in the cache before the rows render them (their logos then show
    at once; wcs/services/store.py). A failure only leaves the badges out."""
    from wcs.services import store
    try:
        store.ensure([(e['media'], e['id']) for e in entries])
    except Exception as exc:
        xbmc.log('[Milionář Žánry] services: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)


def fits_year(row, year):
    """With a year chosen, Populární teď (the last 90 days) and the other decades' best say nothing about it: hidden."""
    if not str(year or '').isdigit():
        return True
    if row in (contract.POPULAR, contract.SERVICES):
        return False
    if row.startswith('gn_decade_'):
        first, last = contract.decade_years(row)
        return first <= int(year) <= last
    return True


def _store(token, view):
    from wcs.library2 import meta
    meta.put(widgets.VIEW_KEY.format(token), view, settings.ttl().get('list') or 86400)


def _fanart(view):
    for entries in view.get('rows', {}).values():
        for entry in entries:
            if entry.get('backdrop'):
                return 'https://image.tmdb.org/t/p/w1280' + entry['backdrop']
    return ''


def load(state, focus=None):
    """Show `state` on the page at once (its hero, buttons and no row of the previous view) and fill it: from the
    cache whole, else row by row. `focus`: the listing card to focus when the listing is there, if the focus is still
    on the button it waits on. True: shown; False: it could not be loaded (the caller goes back); None: a newer load
    of the page took over."""
    token = _signature(state)
    name = widgets.genre_name(state['key'], settings.source().extras(cached_only=True))
    present(state, name)
    if focus is not None:                                         # the rows are gone: the focus waits on the buttons
        xbmc.executebuiltin('SetFocus({})'.format(contract.BUTTON_IDS[0]), True)
    view = widgets.load_view(token)
    if view is None or 'next' not in view:
        view, outcome = None, None
        with pages.Loading(PREFIX, text(S_HEADING).format(name), text(S_LOAD_LIST)) as loading:
            def ready(partial, slot):
                loading.check()
                _store(token, partial)                       # the row reads its cards from the cache
                show_row(state, token, partial, slot, name, focus)
            try:
                view, next_cursor, failed = compute(state, loading, ready)
                if failed:
                    raise IOError('TMDb did not answer')
            except pages.Stale:
                raise
            except Exception as exc:
                xbmc.log('[Milionář Žánry] load failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
                xbmcgui.Dialog().notification('Milionář', text(S_FAILED), xbmcgui.NOTIFICATION_ERROR)
                outcome = False
            else:
                loading.check()
                view['next'] = next_cursor
                _store(token, view)
                outcome = True
        if not outcome:
            return outcome
    for slot in sorted(view.get('rows') or {}, key=int):         # rows the load showed already stay as they are
        show_row(state, token, view, slot, name, focus)
    state['next'] = view.get('next')
    _set('state', json.dumps(state))
    if (view.get('list') or {}).get('more') and state.get('next'):
        prefetch(dict(state, cursor=state['next'], page=state['page'] + 1, stack=[]))
    return True


def years(entries):
    """'2024–2026' of the titles on a page (one year alone, '' without dates)."""
    found = sorted({int(e['year']) for e in entries if str(e.get('year') or '').isdigit() and int(e['year'])})
    if not found:
        return ''
    return str(found[0]) if found[0] == found[-1] else '{}–{}'.format(found[0], found[-1])


def listing_header(name, entries, page):
    """The header of the listing: what is browsed and where, 'Válečný · 2024–2026 · Strana 1'."""
    return ' · '.join(part for part in (name, years(entries), text(S_PAGE).format(page)) if part)


def present(state, name):
    """The page with `state`'s hero and buttons and none of its rows yet, on screen at once."""
    from wcs.skin import hero
    from wcs.skin.hero_contract import slot_count
    pages.cancel(PREFIX)                                          # this view wins over one still loading
    source = settings.source()
    for key, value in labels(state, source).items():
        _set('b.' + key, value)
    _set('name', name)
    _set('size', hero.size(name))
    _set('kicker', kicker(state, source))
    for key in ('listing', 'fanart', 'blur'):
        _set(key, '')
    for n in range(1, slot_count(contract.SEC) + 1):             # which rows have cards (gen_genre: Kodi loads no hidden list)
        _set('has.{}'.format(n), '')
        _set('token.{}'.format(n), '')
    _set('state', json.dumps(state))
    _set('active', 'true')


def show_row(state, token, view, slot, name, focus=None):
    """Row `slot` of `view` on the page (its own token: the rows shown before it do not reload)."""
    from wcs.skin import hero
    slot = str(slot)
    entries = (view.get('rows') or {}).get(slot)
    listing = slot == str(view.get('list_slot', ''))
    if entries is None or not (entries or listing) or _get('token.' + slot) == token:
        return
    if listing:
        _set('listing', listing_header(name, entries, state['page']))
    _row_file(token, slot)
    if not _get('fanart'):
        _set('fanart', _fanart(view))
        _set('blur', hero.blur(_get('fanart')))
    _set('token.' + slot, token)
    _set('has.' + slot, 'true')
    if listing and focus is not None and xbmc.getCondVisibility('Control.HasFocus({})'.format(contract.BUTTON_IDS[0])):
        focus_listing(focus)


def _row_file(token, slot):
    """The row's cards go to its file (wcs/skin/rowfiles.py); a view seen before is there at once."""
    from wcs.library2 import rows
    from wcs.skin import journal, rowfiles
    label = 'Skin.String(mil.{}.{}.{{}})'.format(contract.SEC, slot).format
    params = {'action': 'widget_row', 'row': xbmc.getInfoLabel(label('type')), 'sec': contract.SEC, 'slot': slot,
              'limit': xbmc.getInfoLabel(label('limit')), 'style': xbmc.getInfoLabel(label('style')),
              'click': xbmc.getInfoLabel(label('click')), 'g': token, 'format': '2'}
    name = 'g.{}.{}'.format(token, slot)
    rowfiles.attach(name, PREFIX + 'file.' + slot, PREFIX + 'limit.' + slot)
    cards = journal.capture(params, lambda: rows.run(-1, params))
    if cards is not None:
        rowfiles.refresh(name, cards)
    rowfiles.forget('g.', 100)


class _Silent(object):
    def update(self, _percent, _message):
        pass


def prefetch(state):
    """The next listing page into the cache in the background (no progress: nobody waits for it)."""
    def work():
        try:
            token = _signature(state)
            if widgets.load_view(token) is None:
                view, next_cursor, failed = compute(state, _Silent())
                if not failed:
                    view['next'] = next_cursor
                    _store(token, view)
        except Exception as exc:
            xbmc.log('[Milionář Žánry] prefetch: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGDEBUG)
    thread = threading.Thread(target=work, name='milionar-genre-prefetch')
    thread.daemon = True
    thread.start()


# --------------------------------------------------------------------------- focus

def _focus():
    window = xbmcgui.getCurrentWindowId()
    control = xbmcgui.Window(window).getFocusId()
    position = xbmc.getInfoLabel('Container({}).CurrentItem'.format(control))
    return {'window': window, 'control': control, 'position': int(position or 1) - 1}


def _wait(condition, seconds=3.0):
    monitor = xbmc.Monitor()
    waited = 0.0
    while not xbmc.getCondVisibility(condition) and waited < seconds:
        if monitor.waitForAbort(0.02):
            return False
        waited += 0.02
    return True


def _list_control():
    for n, row in settings.slot_rows():
        if row == contract.LIST:
            return contract.list_id(n)
    rows_ = settings.slot_rows()
    return contract.list_id(rows_[0][0]) if rows_ else contract.BUTTON_IDS[0]


def focus_listing(position):
    """Focus a card of the listing once the reloaded row is there (the first title of a new page)."""
    control = _list_control()
    ready = ('Control.IsVisible({c}) + !Container({c}).IsUpdating + Integer.IsGreater(Container({c}).NumItems,{p})'
             .format(c=control, p=position))
    xbmc.sleep(60)                                # the row starts its reload on the next frame
    _wait(ready)
    xbmc.executebuiltin('SetFocus({},{},absolute)'.format(control, position), True)


def restore(focus):
    if focus['window'] != xbmcgui.getCurrentWindowId():
        xbmc.executebuiltin('ActivateWindow({})'.format(focus['window']))
    _wait('Window.IsActive({w}) + Control.IsVisible({c}) + !Container({c}).IsUpdating'.format(w=focus['window'], c=focus['control']), 2)
    xbmc.executebuiltin('SetFocus({},{},absolute)'.format(focus['control'], focus['position']), True)


# --------------------------------------------------------------------------- actions

def open_genre(params):
    key = params.get('genre', '')
    if not key:
        return
    origin = _focus()
    ensure_rows()
    state = {'key': key, 'filters': default_filters(params.get('mode', '')), 'page': 1, 'cursor': None, 'stack': []}
    _set('owner', pages.menu_item())             # the section keeps the page (gen_cinema.OVERLAYS)
    _set('origin', json.dumps(origin))
    if load(state, 0) is False:
        back()


def ensure_rows():
    """An install that never had the genre page gets its default rows once (wcs/skin/slots.ensure_defaults)."""
    from wcs.skin import slots
    slots.ensure_defaults(contract.SEC)


def go(params):
    """Další / Předchozí stránka of the listing (the cards at its ends)."""
    state = _state()
    if not state:
        return
    previous = dict(state)
    if params.get('go') == 'next' and state.get('next'):
        state['stack'] = state['stack'] + [state.get('cursor')]
        state.update(cursor=state['next'], page=state['page'] + 1)
    elif params.get('go') == 'previous' and state['stack']:
        state.update(cursor=state['stack'][-1], stack=state['stack'][:-1], page=state['page'] - 1)
    else:
        return
    if load(state, 1 if state['page'] > 1 else 0) is False:     # past the "Předchozí stránka" card
        load(previous, 0)


def _menu(options_, current):
    """The short choices (Typ, Řazení, Výběr) in the context menu every hero button uses, over the buttons."""
    from wcs.skin.menu_anchor import anchored
    home = _home()
    home.setProperty('milionar.ctx.active', '1')
    try:
        with anchored():
            index = xbmcgui.Dialog().contextmenu([label for label, _value in options_])
    finally:
        home.clearProperty('milionar.ctx.active')
    return options_[index][1] if 0 <= index < len(options_) and options_[index][1] != current else None


def _select(heading, options_, current):
    values = [value for _label, value in options_]
    index = xbmcgui.Dialog().select(heading, [label for label, _value in options_],
                                    preselect=values.index(current) if current in values else -1)
    return options_[index][1] if index >= 0 else None


def _years():
    from datetime import date
    from wcs.genres import tmdb
    return [(text(S_ALL), '')] + [(str(y), str(y)) for y in range(date.today().year, tmdb.OLDEST_YEAR - 1, -1)]


def _countries(source, current):
    from wcs.genres import tmdb
    names = dict(source.countries())
    top = [(text(S_ALL), '')] + [(names.get(iso, iso), iso) for iso in tmdb.HOME_COUNTRIES + tmdb.TOP_COUNTRIES]
    if current and current not in dict((v, l) for l, v in top):
        top.append((names.get(current, current), current))
    picked = _select(text(35590), top + [(text(S_MORE), '*')], current)
    if picked == '*':
        picked = _select(text(35590), [(name, iso) for iso, name in source.countries()], current)
    return picked


def choose(params):
    """A filter button: its choices, then the view of the new filter from page 1."""
    state = _state()
    name = params.get('f', '')
    if not state or name not in contract.FILTERS:
        return
    filters = state['filters']
    source = settings.source()
    extra = source.extras(cached_only=True)
    if name == 'media':
        both = len(catalog.media_of(state['key'], '', extra)) == 2       # Oboje only where both exist
        offered = [(text(s), v) for v, s in MEDIA if (both if v == '' else catalog.media_of(state['key'], v, extra))]
        value = _menu(offered, filters['media'])
    elif name == 'sort':
        value = _menu([(text(s), v) for v, s in SORTS], filters['sort'])
    elif name == 'origin':
        value = _menu([(text(s), v) for v, s in ORIGINS], filters.get('origin', quality.DEFAULT))
    elif name == 'year':
        value = _select(text(35589), _years(), filters['year'])
    else:
        value = _countries(source, filters['country'])
    if value is None or value == filters.get(name):
        return
    previous = dict(state)
    state['filters'] = dict(filters, **{name: value})
    state.update(page=1, cursor=None, stack=[])
    if load(state) is False:
        load(previous)


def back(_params=None):
    """Zpět (button, Back key): Pro tebe again, on the card the page was opened from."""
    if not _get('active'):
        return
    raw = _get('origin')
    pages.cancel(PREFIX)
    for name in ('active', 'state', 'origin', 'owner'):
        _home().clearProperty(PREFIX + name)
    if raw:
        restore(json.loads(raw))


def run(params):
    action = params.get('action', '')
    if action == 'genre_open':
        open_genre(params)
    elif action == 'genre_filter':
        choose(params)
    elif action == 'genre_page':
        go(params)
    elif action == 'genre_back':
        back(params)
