#!/usr/bin/env python3
"""Generate the genre page on Home (docs/plan/genre-browser/020) from the cinematic hero, button and row templates.

Like the Home detail (gen_detail.py) the page is a group over the sections, shown in the section it was opened from
(gen_cinema.OVERLAYS). Its hero is a section's hero (gen_cinema.PAGES: the title under the cursor, the first row with
titles from a row without them, wcs/skin/hero_source.py), with the filters as its buttons; while no row has a title the
hero names the genre and the filters (Window(Home) properties milionar.genre.*, wcs/genres/page.py). The rows are the
slots of the widget manager's section `genre`; a row's content is empty until the page is open.
Run after changing a template; never edit the generated files by hand.
"""
from pathlib import Path
import re
import sys

import gen_cinema as cinema
import gen_slots

OUT = Path(cinema.ROOT) / 'Includes_MilionarGenre.xml'          # one file for both looks: its rows are the cinema's
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from wcs.genres.contract import ANCHOR, BASE, BUTTON_GROUP, BUTTONS, LIST, PAGE, PREFIX, ROWS, SEC, list_id  # noqa: E402

SLOTS = cinema.slot_count(SEC)
PROPERTY = 'Window(Home).Property(' + PREFIX + '{})'
ACTIVE = 'String.IsEqual({},true)'.format(PROPERTY.format('active'))          # open (its rows keep their content)
SHOWN = '$EXP[MilCineGenreHere]'                                              # on screen
FIELDS = dict(cinema.FIELDS, **cinema.CHANNEL_FIELDS)                         # the hero's texts (its buttons are its own)
FALLBACK = {'Title': 'name', 'Kicker': 'kicker'}                              # no title on the page yet: the genre
TYPE = 'Skin.String(mil.{}.{{n}}.{{field}})'.format(SEC)
USED = '!String.IsEmpty({t}) + !String.IsEqual({t},off)'
RUN = 'RunPlugin(plugin://plugin.video.milionar/?action={})'
BACK = RUN.format('genre_back')


def field(n, name):
    return TYPE.format(n=n, field=name)


def used(n):
    return USED.format(t=field(n, 'type'))


def above(n):
    """Slot n lies above the current row (gen_cinema.above for the page's own rows)."""
    later = ['[String.IsEqual(Window(Home).Property(milionar.row.{}),{}) + String.IsEqual({},true)]'.format(
        SEC, list_id(m), PROPERTY.format('has.{}'.format(m))) for m in range(n + 1, SLOTS + 1)]
    return ' | '.join(later) or 'false'


def buttons():
    lines = ['\t\t\t<control type="grouplist" id="{}">'.format(BUTTON_GROUP),
             '\t\t\t\t<top>388</top>', '\t\t\t\t' + cinema.WIDTH, '\t\t\t\t<height>64</height>',
             '\t\t\t\t<orientation>horizontal</orientation>', '\t\t\t\t<itemgap>24</itemgap>',
             '\t\t\t\t<defaultcontrol always="true">{}</defaultcontrol>'.format(BUTTONS[0][1]),
             '\t\t\t\t<onleft>9000</onleft>', '\t\t\t\t<onright>noop</onright>', '\t\t\t\t<onup>noop</onup>',
             '\t\t\t\t<ondown>{}</ondown>'.format(ROWS), '\t\t\t\t<onback>{}</onback>'.format(ROWS)]
    for name, control in BUTTONS:
        action = BACK if name == 'back' else RUN.format('genre_filter&amp;f=' + name)
        params = {'id': control, 'label': '$INFO[{}]'.format(PROPERTY.format('b.' + name)), 'action': action, 'rows': ROWS,
                  'padding': 24}
        lines += ['\t\t\t\t<include content="MilCineHeroButton">'] + [
            '\t\t\t\t\t<param name="{}" value="{}"/>'.format(key, value) for key, value in params.items()] + ['\t\t\t\t</include>']
    return '\n'.join(lines + ['\t\t\t</control>'])


def build():
    lines = ['<?xml version="1.0" encoding="UTF-8"?>', '<!-- generated by scripts/skin_harness/gen_genre.py: do not edit -->',
             '<includes>']
    for name, values in cinema.named_variables(SEC, FIELDS).items():
        field_name = name[:-len('_' + SEC)]
        extra = [(None, '$INFO[{}]'.format(PROPERTY.format(FALLBACK[field_name])))] if field_name in FALLBACK else []
        lines.extend(cinema.variable(name, values + extra))
    named = cinema.named_expressions(SEC)
    titled = named['Any_' + SEC]
    named['Any_' + SEC] = SHOWN                                               # the buttons stay, also with no title
    for step, _font, _left in cinema.TITLE_FONTS:                             # the genre's name in its own size
        key = 'Size_{}_{}'.format(step, SEC)
        named[key] = '[{}] | [![{}] + String.IsEqual({},{})]'.format(named[key], titled, PROPERTY.format('size'), step)
    # the hero buttons are the filters, not an item's (no HasB<n>, B1Play, Lent); the rows above: above()
    keep = [k for k in named if not re.match(r'(HasB\d|B1Play|Lent|Above)_', k)]
    lines.extend(cinema.expression(name, named[name]) for name in keep)
    for n in range(1, SLOTS + 1):
        lines.append(cinema.expression('Above_{}_{}'.format(SEC, n), above(n)))
        lines += ['\t<variable name="MilGenreContent_{}">'.format(n),
                  '\t\t<value condition="{} + {} + !String.IsEmpty({})">{}$INFO[{}].m3u</value>'.format(
                      ACTIVE, used(n), PROPERTY.format('file.{}'.format(n)), gen_slots.ROW_FILES,
                      PROPERTY.format('file.{}'.format(n))),
                  '\t\t<value></value>', '\t</variable>']
        # the listing's header names the genre, the years of its page and the page: "Válečný · 2024–2026 · Strana 2"
        lines += ['\t<variable name="MilGenreHeader_{}">'.format(n),
                  '\t\t<value condition="String.IsEqual({},{})">$INFO[{}]</value>'.format(
                      field(n, 'type'), LIST, PROPERTY.format('listing')),
                  '\t\t<value>$INFO[{}]</value>'.format(field(n, 'title')), '\t</variable>']
    lines += ['\t<include name="MilCineGenreNavigation">',
              '\t\t<orientation>horizontal</orientation>',
              '\t\t<scrolltime tween="cubic" easing="out">500</scrolltime>',
              '\t\t<onleft>9000</onleft>', '\t\t<onright>noop</onright>',
              ] + cinema.gen_slots.run_lines(BACK, '\t\t', tag='onback') + [
              '\t\t<preloaditems>2</preloaditems>', '\t</include>']
    lines += ['\t<include name="MilionarGenre">', '\t\t<control type="group" id="{}">'.format(BASE),
              '\t\t\t<include>MilionarContentArea</include>',
              '\t\t\t<defaultcontrol>{}</defaultcontrol>'.format(list_id(1)),
              '\t\t\t<visible>{} + System.AddonIsEnabled(plugin.video.milionar)</visible>'.format(SHOWN)]
    ids = {'sec': SEC, 'play': BUTTON_GROUP, 'rows': ROWS}
    progress = [(cinema.item(SEC, n) + '.Property(milionar.hero.watchpercent)', n) for n in range(1, SLOTS + 1)]
    lines.extend(cinema.hero_controls(ids, progress, buttons(), channel=True,
        movie_progress=[(cinema.kind(SEC)['percent'].format(i=cinema.item(SEC, n)), n) for n in range(1, SLOTS + 1)]))
    lines.append(cinema.HERO_ANCHOR.format(id=ANCHOR))
    lines.append(cinema.SECTION_ROWS.format(rows=ROWS, top=cinema.ROWS_TOP, height=cinema.ROWS_HEIGHT, gap=cinema.GAP,
                                            play=BUTTON_GROUP, page=PAGE))
    lines.extend(cinema.ROW_EASE.format(lid=list_id(n), sec=SEC, calm=cinema.CALM) for n in range(1, SLOTS + 1))
    for n in range(1, SLOTS + 1):
        # Kodi fetches no content for a hidden list: like the detail's rows, a row is shown when the prepared view
        # has cards for it (milionar.genre.has.<slot>, wcs/genres/page.py), not when its list has items
        params = {'list_id': list_id(n), 'section': SEC, 'navigation': 'MilCineGenreNavigation', 'known_items': 'true',
                  'fresh': '!String.IsEmpty({})'.format(PROPERTY.format('loading')),
                  'row_visible': '{} + String.IsEqual({},true)'.format(used(n), PROPERTY.format('has.{}'.format(n))),
                  'hide': '$EXP[MilCineAbove_{}_{}]'.format(SEC, n),
                  'widget_header': '$VAR[MilGenreHeader_{}]'.format(n), 'content': '$VAR[MilGenreContent_{}]'.format(n),
                  'limit': '$INFO[{}]'.format(PROPERTY.format('limit.{}'.format(n)))}
        lines += ['\t\t\t<include content="MilCineRowPoster">'] + [
            '\t\t\t\t<param name="{}" value="{}"/>'.format(key, value) for key, value in params.items()] + ['\t\t\t</include>']
    lines.append('\t\t</control>')
    # still loading and no row there yet (wcs/skin/pages.Loading)
    rows_there = ' | '.join('String.IsEqual({},true)'.format(PROPERTY.format('has.{}'.format(n))) for n in range(1, SLOTS + 1))
    lines.append(cinema.loading_spinner('!String.IsEmpty({}) + ![{}]'.format(PROPERTY.format('loading'), rows_there),
                                        'Visible'))
    lines += ['\t\t</control>', '\t</include>', '</includes>']
    return '\n'.join(lines) + '\n'


if __name__ == '__main__':
    from gen_modular import main
    main()
