#!/usr/bin/env python3
"""Render every dialog layout in real Kodi with harmless fixture data; never activate its actions."""
import json
from pathlib import Path
import re
import shutil
import sys
import xml.etree.ElementTree as ET

ROOT = Path(__file__).resolve().parents[2]
LAYOUTS = ROOT / 'resources/skins/Default/1080i'
OUT = ROOT / 'docs/design/dialog-audit'

try:
    import xbmcgui
except ImportError:
    xbmcgui = None


if xbmcgui is not None:
    from wcs.devtools.harness_service import _FixtureDialog

    class AuditDialog(_FixtureDialog):
        def __init__(self, xml, addon_path, controls, props):
            self.ids = controls
            super().__init__(xml, addon_path, 'Default', '1080i', fixture_props=props)

        def onInit(self):
            super().onInit()
            focus = []
            for identifier in self.ids:
                try:
                    control = self.getControl(identifier)
                    if hasattr(control, 'addItems'):
                        items = []
                        for index in range(5):
                            item = xbmcgui.ListItem('Testovací položka s delším názvem {}'.format(index+1))
                            item.setArt({'thumb': str(ROOT/'scripts/dialog_harness/sample_thumb.png'),
                                         'poster': str(ROOT/'scripts/dialog_harness/sample_poster.png')})
                            items.append(item)
                        control.addItems(items)
                        focus.append(identifier)
                    elif isinstance(control, xbmcgui.ControlButton):
                        if not control.getLabel():
                            control.setLabel('Potvrdit' if identifier % 2 else 'Zpět')
                        focus.append(identifier)
                    elif isinstance(control, xbmcgui.ControlTextBox):
                        control.setText('Testovací popis dialogu. Delší text pro kontrolu odstupů a tlačítek. '*3)
                except (RuntimeError, AttributeError, TypeError):
                    continue
            for identifier in focus:
                try:
                    self.setFocusId(identifier)
                    break
                except RuntimeError:
                    continue


def main():
    sys.path.insert(0, str(ROOT/'scripts/dialog_harness'))
    import kodi_live as live
    from render_dialog import BASE_PROPS, PROFILES
    from PIL import Image
    staging = LAYOUTS/'devtools/_dialog_audit'
    staging.mkdir(parents=True, exist_ok=False)
    records = []
    try:
        for skin, short in (('skin.milionar', 'normal'), ('skin.milionar.flat', 'normal-horizont')):
            live.request([{'op': 'skin', 'name': skin}, {'op': 'sleep', 'ms': 2200}])
            native = sorted((ROOT.parent/skin/'xml').glob('Dialog*.xml'))
            native += sorted((ROOT.parent/skin/'xml').glob('Custom_*.xml'))
            sources = [('native', p) for p in native]
            sources += [(str(p.parent.relative_to(LAYOUTS)), p) for p in sorted(LAYOUTS.rglob('Dialog*.xml'))
                        if staging not in p.parents and 'devtools' not in p.parts]
            for index, (area, path) in enumerate(sources):
                tree = ET.parse(path); root = tree.getroot()
                # Fixture snapshots only: no native open/close hooks or plugin directory jobs.
                for node in list(root):
                    if node.tag in ('onload', 'onunload'):
                        root.remove(node)
                ids = sorted({int(c.get('id')) for c in root.iter('control') if (c.get('id') or '').isdigit()})
                ids = sorted(set(ids) | {int(p.get('value')) for p in root.findall(".//param[@name='id']")
                                         if (p.get('value') or '').isdigit()})
                props = dict(BASE_PROPS);props.update(PROFILES['search'])
                for key in re.findall(r'Window(?:\(\))?\.Property\(([^)]+)\)', path.read_text()):
                    if key not in props:
                        props[key] = ('true' if any(s in key.lower() for s in ('show', 'visible', 'enabled')) else
                                      str(ROOT/'scripts/dialog_harness/sample_poster.png') if any(s in key.lower() for s in ('poster', 'thumb', 'fanart')) else
                                      'menu' if key.lower().endswith('state') else 'Testovací text')
                name = '{:02d}-{}-{}'.format(index, area.replace('/', '-'), path.stem)
                staged = staging/(name+'.xml');tree.write(staged, encoding='utf-8', xml_declaration=True)
                screenshot = OUT/'layouts'/short/(name+'.png')
                try:
                    response = live.request([{'op': 'dialog', 'xml': 'devtools/_dialog_audit/'+staged.name,
                        'python_class': 'scripts.skin_harness.audit_dialogs:AuditDialog',
                        'kwargs': {'controls': ids, 'props': props}, 'measure': ids,
                        'settle_ms': 900, 'screenshot': str(screenshot)}])
                    result = response['results'][0]['result']
                    preview = screenshot.with_suffix('.jpg')
                    with Image.open(screenshot) as frame:
                        frame.convert('RGB').save(preview, quality=88)
                    screenshot.unlink()
                    records.append({'skin': skin, 'xml': str(path.relative_to(ROOT.parent)), **result,
                                    'screenshot': str(preview.relative_to(ROOT))})
                    if any('raised' in s for s in result.get('class_trace', [])):
                        print('FIXTURE INIT ERROR:', name, flush=True)
                except (SystemExit, RuntimeError) as exc:
                    records.append({'skin': skin, 'xml': str(path), 'error': str(exc)})
                    print('ERROR:', name, str(exc), flush=True)
                if (index+1) % 10 == 0:
                    print(short, index+1, '/', len(sources), flush=True)
                (OUT/'layouts.json').write_text(json.dumps(records, ensure_ascii=False, indent=2))
    finally:
        shutil.rmtree(staging)
        live.request([{'op': 'close_kept'}, {'op': 'skin', 'name': 'skin.milionar.flat'}])
    print('Audited', len(records), 'dialog layouts.', flush=True)


if __name__ == '__main__':
    main()
