#!/usr/bin/env python3
"""Generate the Flat overlay from the shared functional skin templates.

Only presentation changes: IDs, plugin content, actions, visibility, row types,
context commands and page ownership remain those of the shared generators.
Run this script, then compose_flat.py to update the development installation.
"""
import copy
import json
from pathlib import Path
import xml.etree.ElementTree as ET

from PIL import Image, ImageDraw
import gen_cinema as cinema

ROOT = Path(__file__).resolve().parents[2]
BASE = ROOT / 'resources/skin.milionar'
OUT = ROOT / 'resources/skin-modules/materials/normal'
COLORS = {
    'background': 'FF101211', 'primary_background': 'FF101211', 'secondary_background': '00101211',
    'dialog_tint': 'FF1C201D', 'white': 'FFF3F3EB', 'grey': 'FFB2B8AF',
    'button_focus': 'FFD7FF64', 'button_alt_focus': '40D7FF64', 'selected': 'FFD7FF64',
    'text_shadow': '00000000', 'cinema_shadow': '00000000', 'cinema_bg': 'FF101211',
    'cinema_text': 'FFD2D7CF', 'cinema_dim': 'FFB2B8AF', 'cinema_ink': 'FF101211',
    'cinema_badge': 'FFD7FF64', 'milionar_logo_tint': 'FFF3F3EB', 'milionar_wordmark': 'FFF3F3EB',
    'flat_line': 'FF30372F', 'flat_panel': 'FF1C201D', 'flat_ink': 'FF101211',
}


def element(tag, text=None, **attrs):
    node = ET.Element(tag, attrs)
    node.text = text
    return node


def set_value(node, tag, text):
    child = node.find(tag)
    if child is None:
        child = ET.SubElement(node, tag)
    child.text = str(text)


def image(left, top, width, height, texture, tint=None):
    node = element('control', type='image')
    for tag, val in (('left', left), ('top', top), ('width', width), ('height', height)):
        set_value(node, tag, val)
    node.append(element('texture', texture, **({'colordiffuse': tint} if tint else {})))
    return node


def write_xml(name, root):
    ET.indent(root, space='\t')
    ET.ElementTree(root).write(OUT / 'xml' / name, encoding='utf-8', xml_declaration=True)


def menu_layout(focused):
    layout = element('focusedlayout' if focused else 'itemlayout', width='198', height='64')
    if focused:
        active = image(75, 60, 48, 3, 'colors/white.png', 'button_focus')
        active.append(element('visible', '!Control.HasFocus(9000)'))
        layout.append(active)
        focus = image(8, 0, 182, 56, 'flat/solid.png', 'button_focus')
        focus.append(element('visible', 'Control.HasFocus(9000)'))
        layout.append(focus)
    label = element('control', type='label')
    for tag, val in (('left', '16'), ('top', '0'), ('width', '166'), ('height', '56'),
                     ('font', 'font25_title' if focused else 'font12'), ('align', 'center'), ('aligny', 'center'),
                     ('textcolor', '$VAR[FlatNavText]' if focused else 'grey'), ('label', '$INFO[ListItem.Label]')):
        label.append(element(tag, val))
    label.append(element('scroll', 'true'))
    layout.append(label)
    return layout


def generate_home():
    root = ET.parse(BASE / 'xml/Home.xml').getroot()
    menu = root.find(".//control[@id='9000']")
    parent = next(p for p in root.iter() if menu in list(p))
    # Retain the menu's complete static content and all section contracts.
    for child in list(parent):
        if child.tag == 'control' and child.find("include[.='MilionarSidebarShift']") is not None:
            parent.remove(child)
    for child in list(menu):
        if child.tag in ('left', 'top', 'width', 'bottom', 'movement', 'focusposition', 'itemlayout', 'focusedlayout', 'onup', 'ondown'):
            menu.remove(child)
        elif child.tag == 'include' and (child.text or '') == 'MilionarSidebarHitrect':
            menu.remove(child)
    for tag, val in (('left', '300'), ('top', '36'), ('width', '1300'), ('height', '64'),
                     ('orientation', 'horizontal'), ('movement', '3'), ('focusposition', '0'),
                     ('onup', '700'), ('onleft', '700'), ('onright', '700'), ('onback', '700')):
        menu.append(element(tag, val))
    # A list scrolls to every enabled section, including configurations with more than seven menu entries.
    menu.tag = 'control'
    menu.set('type', 'list')
    menu.append(menu_layout(False))
    menu.append(menu_layout(True))
    utilities = root.find(".//control[@id='700']")
    for tag, val in (('left', '1624'), ('top', '28'), ('width', '240'), ('height', '72'),
                     ('onup', '9000'), ('ondown', '9000'), ('onleft', '9000'), ('align', 'left')):
        set_value(utilities, tag, val)
    for node in utilities.findall('onright'):
        utilities.remove(node)
    set_value(utilities, 'onright', '9000')
    for inc in utilities.findall("include[@content='IconButton']"):
        inc.set('content', 'FlatIconButton')
        inc.append(element('param', name='height', value='72'))
    # Replace Home-only clock/RSS/logo framing; all other windows keep their native bars.
    for p in list(root.iter()):
        for child in list(p):
            if child.tag == 'include' and child.get('content') == 'TopBar':
                p.remove(child)
            elif child.tag == 'include' and (child.text or '') == 'BottomBar':
                p.remove(child)
            elif child.tag == 'control' and (child.find("include[.='MilionarSidebarLogoCollapse']") is not None or child.find("control[@type='rss']") is not None):
                p.remove(child)
    controls = root.find('controls')
    for child in list(controls):
        if child.get('type') == 'multiimage':
            controls.remove(child)
    header = element('control', type='group')
    header.append(element('depth', 'DepthContentPanel'))
    header.append(image(0, 0, 1920, 128, 'colors/white.png', 'background'))
    header.append(image(56, 44, 40, 40, 'special://home/addons/plugin.video.milionar/resources/media/brand/milionar-mark.png', 'white'))
    label = element('control', type='label')
    for tag, value in (('left', '108'), ('top', '34'), ('width', '184'), ('height', '60'),
                       ('font', 'font25_title'), ('aligny', 'center'), ('label', 'MILIONÁŘ')):
        label.append(element(tag, value))
    header.append(label)
    controls.insert(list(controls).index(root.find("controls/control[@type='group']")), header)
    intro = element('control', type='group')
    intro.append(element('left', '56'))
    intro.append(element('top', '176'))
    conditions = []
    for sec, (_base, menu_id, _kind) in cinema.SECTIONS.items():
        rows = ' | '.join('Integer.IsGreater(Container({}).NumItems,0)'.format(cinema.list_id(sec, n))
                          for n in cinema.slot_numbers(sec))
        conditions.append('[String.IsEqual(Container(9000).ListItem.Property(id),{}) + !$EXP[MilCineAny_{}] + [{}]]'
                          .format(menu_id, sec, rows))
    intro.append(element('visible', '!$EXP[MilCineOverlayHere] + [{}]'.format(' | '.join(conditions))))
    for top, height, font, label_text, color in (
        (40, 100, 'font80_title', '$INFO[Container(9000).ListItem.Label]', 'white'),
        (168, 102, 'font12', '$ADDON[plugin.video.milionar 35612]', 'cinema_text'),
    ):
        label = element('control', type='textbox')
        for tag, val in (('top', top), ('height', height), ('width', '900'), ('font', font),
                         ('label', label_text), ('textcolor', color)):
            set_value(label, tag, val)
        intro.append(label)
    controls.append(intro)
    write_xml('Home.xml', root)


def generate_includes():
    root = element('includes')
    nav_text = element('variable', name='FlatNavText')
    nav_text.append(element('value', 'flat_ink', condition='Control.HasFocus(9000) + !System.HasActiveModalDialog'))
    nav_text.append(element('value', 'white'))
    root.append(nav_text)
    play_ink = element('variable', name='FlatPlayInk')
    focused = ' | '.join('Control.HasFocus({})'.format(base + cinema.BUTTON_OFFSETS[0])
                         for base in tuple(cinema.BASES.values()) + (41000,))
    play_ink.append(element('value', 'flat_ink', condition=focused))
    play_ink.append(element('value', 'white'))
    root.append(play_ink)
    animation = element('include', name='Animation_DialogPopupOpenClose')
    for event, start, end in (('WindowOpen', '0', '100'), ('WindowClose', '100', '0')):
        animation.append(element('animation', event, effect='fade', start=start, end=end, time='180'))
    animation.append(element('depth', 'DepthDialog'))
    root.append(animation)
    for name, values in {
        'MilionarContentArea': [('left', '0'), ('top', '128'), ('width', '1920'), ('height', '952')],
        'MilionarContentRightEdge': [('right', '-20')],
        'MilionarSidebarExpandedOnly': [], 'MilionarSidebarShift': [],
        'MilionarSidebarCollapsedOnly': [('visible', 'false')],
        'MilionarBackdropCollapse': [],
    }.items():
        node = element('include', name=name)
        for tag, val in values:
            node.append(element(tag, val))
        root.append(node)
    root.append(element('expression', 'false', name='MilionarSidebarCollapsed'))
    root.append(element('expression', 'false', name='MilionarSidebarOpen'))
    bg = element('include', name='ColoredBackgroundImages')
    bg.append(image(0, 0, 1920, 1440, 'colors/white.png', 'background'))
    root.append(bg)
    # Reuse the complete close and mouse-block contracts of Estuary's dialog panel.
    buttons = ET.parse(BASE / 'xml/Includes_Buttons.xml').getroot()
    utility = copy.deepcopy(buttons.find("include[@name='IconButton']"))
    utility.set('name', 'FlatIconButton')
    button = utility.find('definition/control')
    for tag, value in (('width', '72'), ('radioposx', '20'), ('radioposy', '20'),
                       ('radiowidth', '32'), ('radioheight', '32')):
        set_value(button, tag, value)
    button.find('texturefocus').text = 'flat/solid.png'
    for node in button:
        if node.tag in ('textureradioonfocus', 'textureradioofffocus'):
            node.set('colordiffuse', 'flat_ink')
    root.append(utility)
    for file in [BASE / 'xml/Includes.xml', BASE / 'xml/Includes_Dialogs.xml']:
        if not file.exists():
            continue
        found = ET.parse(file).getroot().find("include[@name='DialogBackgroundCommons']")
        if found is not None:
            panel = copy.deepcopy(found)
            for control in panel.iter('control'):
                texture = control.find('texture')
                if texture is not None and texture.get('colordiffuse') == 'button_focus':
                    texture.text = 'colors/white.png'
                    texture.set('colordiffuse', 'flat_line')
                    set_value(control, 'height', '1')
                    set_value(control, 'top', '69')
                if control.find('label') is not None and control.find('label').text == '$PARAM[header_label]':
                    set_value(control, 'shadowcolor', '00000000')
            root.append(panel)
            break
    write_xml('Includes_Flat.xml', root)


def textures():
    media = OUT / 'media'
    # Keep exact source dimensions for diffuse masks and 9-slice contracts.
    for path in (BASE / 'media/milionar/cinema').glob('*.png'):
        with Image.open(path) as src:
            size = src.size
        name = path.name
        if name in ('mask_music_wide.png', 'mask_banner.png', 'mask_genre.png'):
            band_h = {'mask_music_wide.png': 368, 'mask_banner.png': 552, 'mask_genre.png': 336}[name]
            im = Image.new('RGBA', size, (255, 255, 255, 0))
            y = (size[1] - band_h) // 2
            ImageDraw.Draw(im).rectangle((0, y, size[0] - 1, y + band_h - 1), fill='white')
        elif name.startswith('mask_') or name == 'hero_fade.png':
            im = Image.new('RGBA', size, 'white')
        elif name.startswith('shade_'):
            im = Image.new('RGBA', size, (0, 0, 0, 0))
            # An opaque caption strip keeps names readable without gradients.
            ImageDraw.Draw(im).rectangle((0, int(size[1] * .75), size[0], size[1]), fill=(16, 18, 17, 240))
        elif name in ('focus.png', 'focus_circle.png'):
            im = Image.new('RGBA', size, (255, 255, 255, 0))
            d = ImageDraw.Draw(im)
            d.rectangle((13, 13, size[0]-14, size[1]-14), outline='white', width=3)
        elif name in ('button_ghost.png',):
            im = Image.new('RGBA', size, (28, 32, 29, 255))
            ImageDraw.Draw(im).rectangle((0, 0, size[0]-1, size[1]-1), outline=(66, 74, 63, 255), width=1)
        elif name in ('card.png', 'more.png'):
            im = Image.new('RGBA', size, (28, 32, 29, 255))
        else:
            # Functional icons (spinner, arrows, play) are inherited, not repainted.
            continue
        dest = media / 'milionar/cinema' / name
        dest.parent.mkdir(parents=True, exist_ok=True)
        im.save(dest)
    flat = media / 'flat'
    flat.mkdir(parents=True, exist_ok=True)
    for name, color in (('solid.png', 'white'), ('panel.png', '#1C201D'),
                        ('transparent.png', (255, 255, 255, 0))):
        Image.new('RGBA', (96, 96), color).save(flat / name)
    # Native controls include 20px of invisible texture padding in their geometry.
    # Keep that contract for dialog, settings and keyboard buttons in both Normal skins.
    for name, size, focused in (('dialog-focus.png', 80, True), ('button.png', 80, False),
                                ('round-focus.png', 120, True)):
        im = Image.new('RGBA', (size, size), (255, 255, 255, 0))
        ImageDraw.Draw(im).rectangle((20, 20, size-21, size-21),
                                    fill=(255, 255, 255, 24) if focused else (28, 32, 29, 255),
                                    outline='white' if focused else None, width=3)
        im.save(flat / name)
    for name, ring in (('focus.png', True), ('list-focus.png', False)):
        im = Image.new('RGBA', (96, 96), (255, 255, 255, 24))
        draw = ImageDraw.Draw(im)
        if ring:
            draw.rectangle((0, 0, 95, 95), outline='white', width=3)
        else:
            draw.rectangle((0, 0, 3, 95), fill='white')
        im.save(flat / name)
    wash = Image.new('RGBA', (768, 432), 'white')
    scrim = Image.new('RGBA', (768, 432), (16, 18, 17, 255))

    def smooth(value):
        value = max(0.0, min(1.0, value))
        return value * value * (3 - 2 * value)

    for y in range(432):
        fy = y / 431
        for x in range(768):
            fx = x / 767
            across = smooth((fx - .18) / .72)
            down = 1 - smooth((fy - .4) / .6)
            wash.putpixel((x, y), (255, 255, 255, round(255 * across * down)))
            # At the top and bottom the overlay is exactly the solid carbon ground.
            header = 1 - smooth((fy - .15) / .18)
            floor = smooth((fy - .65) / .35)
            dim = max(.82 - .32 * across, header, floor)
            scrim.putpixel((x, y), (16, 18, 17, round(255 * dim)))
    wash.save(flat / 'cinema-wash.png')
    scrim.save(flat / 'cinema-scrim.png')


def recipe():
    swaps = {}
    for name in ('dialogs/dialog-bg-nobo.png', 'dialogs/dialog-bg.png', 'lists/panel.png'):
        swaps[name] = {'to': 'flat/panel.png', 'border': '0'}
    for name in ('milionar/cinema/button.png', 'milionar/cinema/badge.png', 'milionar/cinema/bar.png'):
        swaps[name] = {'to': 'flat/solid.png', 'border': '0'}
    swaps['lists/focus.png'] = {'to': 'flat/list-focus.png', 'border': '4'}
    for name in ('buttons/button-fo.png', 'buttons/dialogbutton-fo.png'):
        swaps[name] = {'to': 'flat/dialog-focus.png', 'border': '40'}
    swaps['buttons/roundbutton-fo.png'] = {'to': 'flat/round-focus.png', 'border': '0'}
    swaps['osd/fullscreen/buttons/button-fo.png'] = {'to': 'flat/focus.png', 'border': '4'}
    for name in ('buttons/button-nofo.png', 'buttons/dialogbutton-nofo.png', 'buttons/button-alt-nofo.png'):
        swaps[name] = {'to': 'flat/button.png', 'border': '40'}
    swaps['overlays/shadow.png'] = {'to': 'flat/transparent.png', 'border': '0'}
    swaps['frame/InfoBar.png'] = {'to': 'flat/transparent.png', 'border': '0'}
    swaps['milionar/cinema/record_grooves.png'] = {'to': 'flat/transparent.png', 'border': '0'}
    spec = {'includes': ['Includes_Flat.xml'], 'colors': COLORS, 'textures': swaps}
    (OUT / 'compose.json').write_text(json.dumps(spec, indent=2) + '\n')


def main():
    from gen_modular import main as generate
    generate()


if __name__ == '__main__':
    main()
