#!/usr/bin/env python3
"""One Modern presentation, independent menu layouts and reusable material modules."""
import copy
import json
from pathlib import Path
import re
import shutil
import tempfile
import xml.etree.ElementTree as ET

from PIL import Image, ImageDraw
import gen_cinema as cinema
import gen_detail as detail
import gen_genre as genre
import gen_flat as flat
import gen_modern_textures as glass
import gen_cinema_textures as cinema_textures

ROOT = Path(__file__).resolve().parents[2]
BASE = ROOT/'resources/skin.milionar'
OUT = ROOT/'resources/skin-modules'
TEMPLATES = Path(__file__).parent/'templates'


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


def spec(path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2)+'\n')


def rectangle(size, box, color, outline=None):
    image = Image.new('RGBA', size, (255,255,255,0))
    ImageDraw.Draw(image).rectangle(box, fill=color, outline=outline, width=3)
    return image


def main():
    cinema_textures.save(cinema_textures.watch_textures(), str(BASE/'media/milionar/cinema'))
    presentation = ET.parse(TEMPLATES/'modern-presentation.xml').getroot()
    material = json.loads((TEMPLATES/'glass-material.json').read_text())
    shared = OUT/'shared'
    for name, text in (('Includes_MilionarCinema.xml', cinema.build(cinema.MODERN)),
                       ('Includes_MilionarDetail.xml', detail.build(cinema.MODERN)),
                       ('Includes_MilionarGenre.xml', genre.build())):
        write(BASE/'xml'/name, ET.fromstring(text))
        stale=shared/'xml'/name
        if stale.exists():stale.unlink()
    common = ET.Element('includes')
    material_names = ('DialogBackgroundCommons', 'Animation_DialogPopupOpenClose')
    for node in presentation:
        if node.get('name') not in material_names:
            common.append(copy.deepcopy(node))
    # Native list labels have no focusedcolor: pair their ink with the container's fill.
    roots = [ET.parse(path).getroot() for path in (BASE/'xml').glob('*.xml')]
    sources = '\n'.join(ET.tostring(root, encoding='unicode') for root in roots)
    containers = set(re.findall(r'Milionar(Row|Selected)Ink_(\d+)', sources))
    calls = [node for root in roots for node in root.iter('include') if node.get('content')]
    for definition in (node for root in roots for node in root.findall('include')):
        parameters = set(re.findall(r'Milionar(Row|Selected)Ink_\$PARAM\[(\w+)\]', ET.tostring(definition, encoding='unicode')))
        for call in calls:
            if call.get('content') != definition.get('name'):
                continue
            containers.update((kind, param.get('value')) for kind, parameter in parameters for param in call.findall('param')
                              if param.get('name') == parameter and param.get('value', '').isdigit())
    for kind, identifier in sorted(containers, key=lambda pair: (pair[0], int(pair[1]))):
        variable = ET.SubElement(common, 'variable', name='Milionar'+kind+'Ink_'+identifier)
        ET.SubElement(variable, 'value', condition='Control.HasFocus('+identifier+')').text = 'flat_ink'
        ET.SubElement(variable, 'value').text = 'flat_alt_ink' if kind == 'Selected' else 'white'
    # Backgrounds belong to the common presentation, independently of the surface material.
    background_names = ('modern/ambient_shade.png', 'modern/hero_scrim.png', 'milionar/cinema/hero_fade.png', 'modern/aurora.jpg')
    for texture in common.iter('texture'):
        for key in ('diffuse',):
            if texture.get(key) in background_names:
                texture.set(key, 'presentation/'+Path(texture.get(key)).name)
        if texture.text in background_names:
            texture.text = 'presentation/'+Path(texture.text).name
    spec(shared/'compose.json', {'includes':['Includes_Presentation.xml']})
    images = glass.build()
    for name in background_names:
        path=shared/'media/presentation'/Path(name).name
        path.parent.mkdir(parents=True,exist_ok=True)
        if name.endswith('.jpg'):glass.aurora().save(path,quality=88,optimize=True,progressive=True)
        else:images[name].save(path)

    with tempfile.TemporaryDirectory(prefix='milionar-material-') as temp:
        flat.OUT = Path(temp)
        (flat.OUT/'xml').mkdir()
        flat.generate_home();flat.generate_includes();flat.textures();flat.recipe()
        layout = ET.parse(flat.OUT/'xml/Includes_Flat.xml').getroot()
        # Text on the accent follows the colour theme, independently of the material.
        for variable in layout.findall('variable'):
            common.append(copy.deepcopy(variable))
        write(shared/'xml/Includes_Presentation.xml', common)
        normal_recipe = json.loads((flat.OUT/'compose.json').read_text())
        normal = OUT/'materials/normal'
        normal.mkdir(parents=True, exist_ok=True)
        shutil.copytree(flat.OUT/'media', normal/'media', dirs_exist_ok=True)
        normal_images = {
            'milionar/cinema/focus.png': rectangle((120,120),(25,25,94,94),None,'white'),
            'milionar/cinema/button.png': Image.new('RGBA',(64,64),'white'),
            'flat/sidebar.png': rectangle((120,120),(20,20,99,99),(28,32,29,255)),
            'flat/menu-focus.png': rectangle((112,64),(24,6,87,57),'white'),
            'material/nav-focus.png': rectangle((192,64),(4,4,187,59),'white'),
        }
        for name,image in normal_images.items():
            path=normal/'media'/name;path.parent.mkdir(parents=True,exist_ok=True);image.save(path)
        normal_recipe['textures'].update({
            'modern/sidebar.png': {'to':'flat/sidebar.png','border':'52'},
            'modern/menu_focus.png': {'to':'flat/menu-focus.png','border':'42,22,42,22'},
        })
        # Current Kodi accent stays global; neither material chooses a different accent.
        for name in ('button_focus','button_alt_focus','selected','cinema_badge'):
            normal_recipe['colors'].pop(name,None)
        normal_recipe['colors'].update({key:value for key,value in material['colors'].items()
                                       if key in ('background','cinema_bg','cinema_dim','ambient_light','ambient_light_half','sidebar_idle','sidebar_active')})
        normal_recipe['includes']=['Includes_Material.xml']
        # The common rows use Modern's geometry and texture canvas even with square materials.
        normal_recipe['textures'].pop('milionar/cinema/button.png',None)
        normal_recipe['patches']=[]
        normal_nodes=ET.Element('includes')
        for node in layout:
            if node.get('name') in material_names:
                normal_nodes.append(copy.deepcopy(node))
        write(normal/'xml/Includes_Material.xml',normal_nodes)
        spec(normal/'compose.json',normal_recipe)

        horizontal=OUT/'layouts/horizontal'
        home=ET.parse(flat.OUT/'xml/Home.xml').getroot()
        header=next(c for c in home.findall('controls/control') if c.find("control/label[.='MILIONÁŘ']") is not None)
        panel=header.find('control')
        for tag,value in (('left',12),('top',-4),('width',1896),('height',136)):
            flat.set_value(panel,tag,value)
        panel.find('texture').text='modern/sidebar.png';panel.find('texture').attrib={'border':'52'}
        focus=home.find(".//control[@id='9000']/focusedlayout/control/texture[.='flat/solid.png']")
        focus.text='material/nav-focus.png';focus.set('border','24')
        write(horizontal/'xml/Home.xml',home)
        definitions=ET.Element('includes')
        for node in layout:
            if node.tag != 'variable' and node.get('name') not in material_names:
                definitions.append(copy.deepcopy(node))
        for texture in definitions.iter():
            if texture.tag=='texturefocus' and texture.text=='flat/solid.png':texture.text='buttons/roundbutton-fo.png'
        write(horizontal/'xml/Includes_Layout.xml',definitions)
        patches=[]
        for name in ('Includes_MilionarCinema.xml','Includes_MilionarDetail.xml','Includes_MilionarGenre.xml'):
            text=(BASE/'xml'/name).read_text();old='<top>496</top>'
            if old in text:patches.append({'file':'xml/'+name,'find':old,'replace':'<top>452</top>','count':text.count(old)})
        # No sidebar is present to reveal extra sharp artwork on collapse.
        patches.append({'file':'xml/Includes_Presentation.xml','find':'<left>462</left>','replace':'<left>0</left>',
                        'count':(shared/'xml/Includes_Presentation.xml').read_text().count('<left>462</left>')})
        patches.append({'file':'xml/Includes_Presentation.xml','find':'<width>1458</width>','replace':'<width>1920</width>',
                        'count':(shared/'xml/Includes_Presentation.xml').read_text().count('<width>1458</width>')})
        spec(horizontal/'compose.json',{'includes':['Includes_Layout.xml'],'patches':patches})

    styled=OUT/'materials/glass'
    for name,image in images.items():
        if name in background_names:continue
        path=styled/'media'/name;path.parent.mkdir(parents=True,exist_ok=True);image.save(path)
    path=styled/'media/material/nav-focus.png';path.parent.mkdir(parents=True,exist_ok=True)
    glass.lit((192,64),(4,4,188,60),glass.RADIUS,glow=0).save(path)
    nodes=ET.Element('includes')
    for node in presentation:
        if node.get('name') in material_names:nodes.append(copy.deepcopy(node))
    write(styled/'xml/Includes_Material.xml',nodes)
    sidebar=OUT/'layouts/sidebar'
    spec(sidebar/'compose.json',{'patches':material.pop('patches')})
    material['includes']=['Includes_Material.xml']
    spec(styled/'compose.json',material)
    settings=ET.parse(TEMPLATES/'appearance-settings.xml').getroot()
    write(OUT/'settings.xml',settings)
    print('generated one shared presentation, two menu modules and two materials')


if __name__=='__main__':main()
