#!/usr/bin/env python3
"""Generate resources/skins/Default/1080i/vinyl/DialogVinylRadioStudio.xml: the Radio Studio card (Vinyl radio).

The same large rounded translucent card as the Millionaire game, built from the blocks of gen_modern_game.py (panel,
button, tab_button, label, textures, tokens) and the hint bar of gen_ai_costs.py (docs/plan/vinyl-radio/020). Left
column: the pages (Právě vysílá, Z playlistu, Nové vysílání, Záznamy) and Zavřít. Right: the page chosen by the window
property `VinylRadio.Page`:
- live | playlists | records: one list with covers (id 9720),
- create: one list of setting rows, a name and its value (id 9730),
- start (Vinyl's Studio lobby): on the left the source, "Spustit vysílání" (9750), "Spustit teď — {show}" (9752) and the
  moderators (9740, OK picks one); on the right every setting of the lobby (9760).
Rows are filled by wcs/vinyl/radio_studio.py, whose constants are these ids. Run after changing this file; never edit
the XML by hand.
"""
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import gen_ai_costs as a  # noqa: E402
import gen_modern_game as g  # noqa: E402
from functools import partial  # noqa: E402
from xml.sax.saxutils import escape  # noqa: E402

OUT = os.path.join(HERE, '..', '..', 'resources', 'skins', 'Default', '1080i', 'vinyl', 'DialogVinylRadioStudio.xml')

PAGE_IDS = {'live': 9701, 'playlists': 9702, 'create': 9703, 'records': 9704}
CLOSE = 9709
LIST, SETTINGS, MODERATORS, START, QUICK, START_SETTINGS = 9720, 9730, 9740, 9750, 9752, 9760
PAD = g.PAD
NAV_X, NAV_W, NAV_H, NAV_GAP, NAV_Y = PAD, 330, 76, 14, 130
CLOSE_Y = NAV_Y + 4 * (NAV_H + NAV_GAP) + 40
CONTENT_X = 420
CONTENT_W = g.CARD_W - PAD - CONTENT_X                    # 1244
LIST_Y, LIST_H, ROW_H = 222, 640, 96
SET_Y, SET_H, SET_ROW_H = 222, 640, 64
# the start page: the left column launches and picks the moderator, the right one holds the settings
LEFT_W, RIGHT_X = 576, 616
RIGHT_W = CONTENT_W - RIGHT_X                             # 628
MOD_Y, MOD_ROW_H, MOD_ROWS = 500, 93, 4
START_SET_Y, START_SET_ROW_H, START_SET_ROWS = 196, 60, 11

PAGE = 'Window.Property(VinylRadio.Page)'
TAB = 'Window.Property(VinylRadio.Tab)'


def str_id(number):
    return a.str_id(number)


def prop(name):
    return '$INFO[Window.Property(VinylRadio.{})]'.format(name)


def on_page(*names):
    return ' | '.join('String.IsEqual({},{})'.format(PAGE, n) for n in names)


def has(name):
    return '!String.IsEmpty(Window.Property(VinylRadio.{}))'.format(name)


def item(name):
    return '$INFO[ListItem.Property({})]'.format(name)


def item_is(name):
    return 'String.IsEqual(ListItem.Property({}),true)'.format(name)


def content_target():
    """Right from the left column: the focusable part of the open page."""
    return ((on_page('live', 'playlists', 'records'), LIST), (on_page('create'), SETTINGS), (on_page('start'), START))


def back_target():
    """Left from the page: the button of the page it belongs to (VinylRadio.Tab), else the first one."""
    targets = [('String.IsEqual({},{})'.format(TAB, page), ident) for page, ident in PAGE_IDS.items()]
    return tuple(targets + [('String.IsEmpty({})'.format(TAB), PAGE_IDS['live'])])


# ---- the rows of the lists
def focus_frame(w, h, indent, visible):
    return (g.image(g.BTN_TEX, 0, 2, w, h - 4, indent, color=g.BTN_FOCUS_FILL, border=g.R_BTN, visible=visible) +
            g.image(g.BTN_STROKE_TEX, 0, 2, w, h - 4, indent, color=g.GOLD, border=g.R_BTN, visible=visible,
                    animations=[('effect="fade" start="62" end="100" time="900" tween="sine" easing="inout" pulse="true"',
                                 'Visible')]))


def media_row(focused, indent, visible=None):
    """A broadcast, a playlist or a recording: cover, title, a line under it and a note on the right."""
    i = indent + '    '
    w, h = CONTENT_W, ROW_H
    ink, sub, note = (g.INK, g.INK, g.INK) if focused else (g.TXT, g.DIM, g.GOLD)

    def show(extra=None):
        return ' + '.join(p for p in (visible, extra) if p) or None

    lines = focus_frame(w, h, i, show()) if focused else g.image(g.WHITE_TEX, 24, h - 1, w - 48, 1, i, color='14FFFFFF',
                                                                    visible=show())
    lines += g.image(g.BTN_TEX, 16, 10, 76, 76, i, color='33000000', border=g.R_BTN, visible=show())
    lines += g.image('$INFO[ListItem.Art(thumb)]', 20, 14, 68, 68, i, aspect='scale', visible=show())
    lines += g.label(item('c1'), 112, 12, w - 112 - 300, 40, i, font='font27', color=ink, visible=show())
    lines += g.label(item('c2'), 112, 50, w - 112 - 300, 34, i, font='font25', color=sub, visible=show())
    lines += g.label(item('c3'), w - 300, 12, 276, 40, i, font='font25_title', color=note, align='right', visible=show())
    lines += g.label(item('c4'), w - 300, 50, 276, 34, i, font='font25', color=sub, align='right', visible=show())
    return lines


def setting_row(focused, indent, visible=None, w=CONTENT_W, h=SET_ROW_H, name_w=520):
    """A setting: its name and its value; the start row (`start`) is a gold action with the play icon."""
    i = indent + '    '
    ink = g.INK if focused else g.TXT
    value = g.INK if focused else g.GOLD

    def show(extra=None):
        return ' + '.join(p for p in (visible, extra) if p) or None

    plain, start = show('!' + item_is('start')), show(item_is('start'))
    lines = focus_frame(w, h, i, show()) if focused else g.image(g.WHITE_TEX, 24, h - 1, w - 48, 1, i, color='14FFFFFF',
                                                                    visible=show())
    lines += g.label(item('c1'), 28, 0, name_w, h, i, font='font27', color=ink, visible=plain)
    lines += g.label(item('c2'), name_w + 40, 0, w - name_w - 68, h, i, font='font27', color=value, align='right',
                     visible=plain, scroll=focused)
    lines += g.image('osd/fullscreen/buttons/play.png', 28, (h - 32) // 2, 32, 32, i, aspect='keep',
                     color=g.INK if focused else g.GOLD, visible=start)
    lines += g.label(item('c1'), 76, 0, w - 104, h, i, font='font32_title',
                     color=g.INK if focused else g.GOLD, visible=start)
    return lines


def moderator_row(focused, indent, visible=None):
    """A moderator: its name and its description; the one this page will start with has a gold ring."""
    i = indent + '    '
    w, h = LEFT_W, MOD_ROW_H

    def show(extra=None):
        return ' + '.join(p for p in (visible, extra) if p) or None

    if focused:
        lines = focus_frame(w, h, i, show())
    else:
        lines = (g.image(g.BTN_TEX, 0, 4, w, h - 8, i, color=g.BTN_FILL, border=g.R_BTN, visible=show()) +
                 g.image(g.BTN_STROKE_TEX, 0, 4, w, h - 8, i, color=g.PANEL_STROKE, border=g.R_BTN,
                         visible=show('!' + item_is('current'))) +
                 g.image(g.BTN_STROKE_TEX, 0, 4, w, h - 8, i, color=g.GOLD, border=g.R_BTN, visible=show(item_is('current'))))
    name, sub = (g.INK, g.INK) if focused else (g.TXT, g.DIM)
    lines += g.label(item('c1'), 24, 10, w - 48, 40, i, font='font27', color=name, visible=show('!' + item_is('current')))
    lines += g.label(item('c1'), 24, 10, w - 48, 40, i, font='font27', color=g.INK if focused else g.GOLD,
                     visible=show(item_is('current')))
    lines += g.label(item('c2'), 24, 48, w - 48, 34, i, font='font25', color=sub, visible=show(), scroll=focused)
    return lines


def layouts(drawing, list_id, width, height):
    """The plain item and the selected one: the cream look only while the list has the focus (Kodi draws the selected
    row with the focused layout even when the focus is elsewhere)."""
    has_focus = 'Control.HasFocus({})'.format(list_id)

    def wrap(tag, lines):
        return ['{}<{} width="{}" height="{}">'.format('            ', tag, width, height)] + lines + \
               ['{}</{}>'.format('            ', tag)]

    return (wrap('itemlayout', drawing(False, '            ')) +
            wrap('focusedlayout', drawing(False, '            ', '!' + has_focus) + drawing(True, '            ', has_focus)))


def list_control(ident, x, y, w, h, orientation, links, drawing, item_w, item_h, indent, visible):
    i = indent + '    '
    body = g.geometry(x, y, w, h, i) + g.nav(*links, indent=i) + [
        g.tag('orientation', orientation, i), g.tag('scrolltime', '180', i)]
    body.append(g.tag('visible', escape(visible), i))
    body += layouts(drawing, ident, item_w, item_h)
    return g.control('list', body, indent, id=ident)


# ---- the pages
def heading(indent, visible):
    i = indent + '    '
    return g.group([g.label(prop('Heading'), 0, 108, CONTENT_W, 56, i, font='font37_title', color=g.TXT, scroll=True),
                    g.label(prop('Lead'), 0, 162, CONTENT_W, 40, i, font='font27', color=g.SUB, scroll=True)],
                   0, 0, CONTENT_W, 220, indent, visible=visible, animations=g.screen_animations())


def list_pages(indent):
    i = indent + '    '
    visible = on_page('live', 'playlists', 'records')
    return [heading(i, visible),
            list_control(LIST, 0, LIST_Y, CONTENT_W, LIST_H, 'vertical', (None, None, back_target(), None),
                         media_row, CONTENT_W, ROW_H, i, visible),
            g.label(prop('Empty'), 0, LIST_Y + 40, CONTENT_W, 60, i, font='font32', color=g.DIM,
                    visible='[{}] + {}'.format(visible, has('Empty')))]


def setting_pages(indent):
    i = indent + '    '
    visible = on_page('create')
    return [heading(i, visible),
            list_control(SETTINGS, 0, SET_Y, CONTENT_W, SET_H, 'vertical', (None, None, back_target(), None),
                         setting_row, CONTENT_W, SET_ROW_H, i, visible)]


def start_page(indent):
    """Vinyl's Studio lobby: launch and the moderators on the left, the settings on the right."""
    i = indent + '    '
    shown = on_page('start')
    to_settings = START_SETTINGS
    return [g.group([
        g.label(prop('Kicker'), 0, 108, LEFT_W, 36, i, font='font25_title', color=g.DIM),
        g.label(prop('Title'), 0, 140, LEFT_W, 64, i, font='font45_title', color=g.TXT, scroll=True),
        g.textbox(prop('Facts'), 0, 210, LEFT_W, 70, i, font='font25', color=g.SUB),
        g.button(START, str_id(33173), 0, 288, LEFT_W, 84, i, (None, QUICK, back_target(), to_settings),
                 icon='osd/fullscreen/buttons/play.png', primary=True),
        g.button(QUICK, prop('QuickLabel'), 0, 384, LEFT_W, 64, i, (START, MODERATORS, back_target(), to_settings),
                 icon='icons/infodialogs/info.png'),
        g.label(str_id(33179), 0, 462, LEFT_W, 34, i, font='font25_title', color=g.SUB),
        list_control(MODERATORS, 0, MOD_Y, LEFT_W, MOD_ROW_H * MOD_ROWS, 'vertical', (QUICK, None, back_target(), to_settings),
                     moderator_row, LEFT_W, MOD_ROW_H, i, shown),
        g.label(str_id(33174), RIGHT_X, 108, RIGHT_W, 36, i, font='font25_title', color=g.SUB),
        g.label(str_id(33175), RIGHT_X, 144, RIGHT_W, 34, i, font='font25', color=g.DIM, scroll=True),
        list_control(START_SETTINGS, RIGHT_X, START_SET_Y, RIGHT_W, START_SET_ROW_H * START_SET_ROWS, 'vertical',
                     (None, None, MODERATORS, None),
                     partial(setting_row, w=RIGHT_W, h=START_SET_ROW_H, name_w=250), RIGHT_W, START_SET_ROW_H, i, shown)],
        0, 0, CONTENT_W, g.CARD_H, indent, visible=shown, animations=g.screen_animations())]


def busy(indent):
    i = indent + '    '
    return g.group([g.dots(0, 0, i)], (CONTENT_W - 92) // 2, 520, 92, 20, indent, visible=has('Busy'))


def header(indent):
    i = indent + '    '
    return g.group([
        g.image(g.M('brand/milionar-mark.png'), PAD, 30, 52, 52, i, aspect='keep'),
        g.label(prop('TitleSpaced'), PAD + 68, 30, 600, 52, i, font='font25_title', color=g.SUB),
        g.label(prop('Note'), g.CARD_W - PAD - 760, 30, 760, 52, i, font='font25', color=g.SUB, align='right', scroll=True)],
        0, 0, g.CARD_W, 100, indent)


def card(indent):
    i = indent + '    '
    labels = {'live': 33101, 'playlists': 33145, 'create': 33103, 'records': 33104}
    icons = {'live': 'icons/infodialogs/info.png', 'playlists': 'osd/fullscreen/buttons/playlist.png',
             'create': 'icons/infodialogs/cinema.png', 'records': 'osd/fullscreen/buttons/repeat-all.png'}
    order = list(PAGE_IDS)
    body = [
        g.image(g.CARD_TEX, 0, 0, g.CARD_W, g.CARD_H, i, color=g.CARD_FILL, border=g.R_CARD),
        # the cover of what the page is about, as a soft glow (a tiny texture stretched): right side, faded in from
        # the left like the game's backdrop
        g.image(prop('Fanart'), g.CARD_W - 840, 0, 840, g.CARD_H, i, diffuse='modern_fanart_mask.png', aspect='scale',
                color='408E8E92', visible=has('Fanart') + ' + ' + on_page('start')),
        g.image(g.CARD_STROKE_TEX, 0, 0, g.CARD_W, g.CARD_H, i, color=g.CARD_STROKE, border=g.R_CARD),
        header(i)]
    for index, page in enumerate(order):
        up = PAGE_IDS[order[index - 1]] if index else None
        down = PAGE_IDS[order[index + 1]] if index < len(order) - 1 else CLOSE
        chosen = 'String.IsEqual({},{})'.format(TAB, page)
        body.append(g.tab_button(PAGE_IDS[page], chosen, str_id(labels[page]), NAV_X, NAV_Y + index * (NAV_H + NAV_GAP),
                                 NAV_W, NAV_H, i, (up, down, None, content_target()), icons[page]))
    body.append(g.image(g.WHITE_TEX, NAV_X, CLOSE_Y - 22, NAV_W, 1, i, color='28FFFFFF'))
    body.append(g.button(CLOSE, str_id(33149), NAV_X, CLOSE_Y, NAV_W, 72, i,
                         (PAGE_IDS[order[-1]], None, None, content_target()), icon='dialogs/close.png'))
    content = list_pages(i + '    ') + setting_pages(i + '    ') + start_page(i + '    ') + [busy(i + '    ')]
    body.append(g.group(content, CONTENT_X, 0, CONTENT_W, g.CARD_H, i))
    body.append(a.hint_bar(i))
    return g.group(body, g.CARD_X, g.CARD_Y, g.CARD_W, g.CARD_H, indent,
                   animations=[('effect="fade" start="0" end="100" time="380" tween="cubic" easing="out"', 'WindowOpen'),
                               ('effect="zoom" start="94" end="100" center="auto" time="420" tween="cubic" easing="out"', 'WindowOpen'),
                               ('effect="fade" start="100" end="0" time="220"', 'WindowClose'),
                               ('effect="zoom" start="100" end="96" center="auto" time="220" tween="cubic" easing="in"', 'WindowClose')])


def build():
    indent = '        '
    lines = ['<?xml version="1.0" encoding="UTF-8"?>',
             '<!-- generated by scripts/game_dialog/gen_radio_studio.py: do not edit. The Radio Studio card'
             ' (wcs/vinyl/radio_studio.py); the page is VinylRadio.Page, control ids are listed in that module. -->',
             '<window type="dialog">', '    <defaultcontrol>{}</defaultcontrol>'.format(PAGE_IDS['live']),
             '    <controls>'] + g.image(g.WHITE_TEX, 0, 0, 1920, 1080, '        ', color='C8000000',
                                          animations=[('effect="fade" start="0" end="100" time="300"', 'WindowOpen'),
                                                      ('effect="fade" start="100" end="0" time="220"', 'WindowClose')]) + card(indent) + [
        '    </controls>', '</window>']
    return '\n'.join(lines) + '\n'


if __name__ == '__main__':
    text = build()
    with open(OUT, 'w', encoding='utf-8') as handle:
        handle.write(text)
    print('wrote', os.path.relpath(OUT), len(text.splitlines()), 'lines')
