#!/usr/bin/env python3
"""Share Normal materials from Horizont; Modern materials remain owned by Modern.

The composition recipes select a material family without replacing the layout's
Home, content IDs or navigation. PNGs are imported by compose, not copied here.
"""
import copy
import json
import sys
from pathlib import Path
import xml.etree.ElementTree as ET

ROOT = Path(__file__).resolve().parents[2]
BASE = ROOT / 'resources/skin.milionar'
sys.path.insert(0, str(ROOT))
from wcs.skin.palette import PALETTE, ACCENT_INK, accent_text, blend, contrast_ink


def write(path, root):
    ET.indent(root, space='\t')
    ET.ElementTree(root).write(path, encoding='utf-8', xml_declaration=True)


def vinyl(style):
    """Two material variants of one functional dialog, never two independently maintained templates."""
    folder = ROOT / 'resources/skins/Default/1080i/vinyl'
    source = folder / 'DialogVinylDetail.xml'
    skin = 'skin-modules/materials/glass' if style == 'Modern' else 'skin-modules/materials/normal'
    prefix = 'special://home/addons/plugin.video.milionar/resources/' + skin + '/media/'
    root = ET.fromstring(source.read_text().replace('/resources/skin.milionar/media/', '/resources/' + skin + '/media/'))
    for texture in root.iter('texture'):
        if texture.get('diffuse') == prefix + 'milionar/cinema/hero_fade.png':
            texture.set('diffuse', 'special://home/addons/plugin.video.milionar/resources/skin-modules/shared/media/presentation/hero_fade.png')
    for control in root.iter('control'):
        tex, aspect = control.find('texture'), control.find('aspectratio')
        if tex is not None and aspect is not None and prefix in (tex.text or ''):
            aspect.text = 'stretch'
        focused = control.find('focusedcolor')
        if focused is not None:
            focused.text = ACCENT_INK
    for node in root.iter():
        if node.tag in ('texture', 'texturefocus') and (node.text or '').endswith('/cinema/button.png') and style == 'Normal':
            node.text = prefix + 'flat/solid.png'
            node.set('border', '0')
    for label in root.findall(".//focusedlayout/control[@type='label']/textcolor"):
        label.text = ACCENT_INK
    backdrop = root.find('controls/control/texture')
    backdrop.text = 'colors/white.png'
    backdrop.attrib = {'colordiffuse': 'D9050A14' if style == 'Modern' else 'E0101211'}
    write(folder / ('DialogVinylDetail' + style + '.xml'), root)


def accents():
    """Only accent tokens go in Kodi colour themes; backgrounds belong to the material family."""
    themes = {path.name: ET.parse(path).getroot().findtext("color[@name='button_focus']")[2:]
              for path in (BASE / 'colors').glob('*.xml') if path.name != 'defaults.xml'}
    themes.update({filename: color for filename, color, _label in PALETTE})
    for filename, color in themes.items():
        root = ET.Element('colors')
        ink = contrast_ink(color)
        for name, value in {'button_focus': 'FF' + color, 'button_alt_focus': '80' + color,
                            'selected': 'FF' + color, 'cinema_badge': 'FF' + color, 'sidebar_active': '3D' + color,
                            'flat_ink': ink, 'cinema_ink': ink, 'accent_text': accent_text(color),
                            'flat_alt_ink': contrast_ink(blend(color, '1A2123', 128/255)),
                            'accent_soft': '33' + color}.items():
            ET.SubElement(root, 'color', name=name).text = value
        write(BASE / 'colors' / filename, root)


def main():
    accents()
    for style in ('Normal', 'Modern'):
        vinyl(style)
    print('generated two shared material families')


if __name__ == '__main__':
    main()
