"""Render the documentation gallery using real, Config-injected skin painters.

Run from the repository root with the docs extra installed. These offline
examples use a declared synthetic waveform, not a rendered song or a live UI.
"""
import json
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw
from pyiv import get_injector

from submediant import FixedRange, RangedInteger
from submediant.component_model import (
    ComponentDefinition, ComponentPanel, DisplayElement, DisplayKind, StereoLevelDisplay,
    DisplayOrientation, NumericControlKind, NumericDisplay, Presentation, SignalRef,
    audio_out,
)
from submediant.equipment_skin_config import EquipmentSkinConfig
from submediant.equipment_skins import EquipmentSkinFactory
from submediant.performance_layout import ComponentGroup, DisplayId, DisplayPlacement, Rect
from submediant.skin_model import (
    AMP, ATOMCORE, BASS, DIAGNOSTIC, DRUM_MACHINE, GUITAR, LED_CITY, MIXER, NAVY,
)

THEMES = (ATOMCORE, LED_CITY, GUITAR, DIAGNOSTIC, AMP, MIXER, DRUM_MACHINE, BASS, NAVY)
OUTPUT = Path('build/docs/components')


# start-declarations

def make_elements():
    gain = FixedRange(0, 1, 2, 3).bind('.65')
    fader = FixedRange(0, 1, 2, 3).bind('.35')
    frequency = RangedInteger(440, 20, 999, unit='Hz')

    def numeric(id_, label, value, control):
        display = NumericDisplay(value, control)
        return DisplayElement(id_, label, DisplayKind.SETTING,
                              value=display.text, numeric=display)

    signal = SignalRef(('demo',), 'out')
    return (
        numeric('gain', 'GAIN', gain, NumericControlKind.KNOB),
        numeric('fader', 'FADER', fader, NumericControlKind.SLIDER),
        numeric('frequency', 'FREQUENCY', frequency, NumericControlKind.READOUT),
        DisplayElement('status', 'STATUS', DisplayKind.SETTING, value='DEMO / ON'),
        DisplayElement('wave', 'WAVEFORM', DisplayKind.WAVEFORM, signal=signal),
        DisplayElement('meter', 'METER', DisplayKind.METER, signal=signal),
        DisplayElement('led', 'LED STRIP', DisplayKind.LED_STRIP, signal=signal),
        DisplayElement('vertical-led', 'OUT', DisplayKind.LED_STRIP,
                       signal=signal, orientation=DisplayOrientation.VERTICAL),
        StereoLevelDisplay('stereo-level', 'L/R', signal=signal,right_signal=SignalRef(('demo',),'right')),
    )

# end-declarations


# start-binding

def skin_factory():
    # The composition root owns Config/injection. Painters receive typed objects.
    return get_injector(EquipmentSkinConfig()).inject(EquipmentSkinFactory)

# end-binding


def demo_signal():
    t = np.arange(480) / 24_000
    values = .32 * np.sin(2 * np.pi * 440 * t)
    history = np.linspace(.03, .32 / np.sqrt(2), 32)
    return values, history


# start-painting

def paint_panel(factory, theme, elements, *, hardware=True,
                presentation=Presentation.STANDARD, columns=4):
    renderer = factory.bind(theme).renderer
    component = ComponentDefinition(
        'demo', 'Component demonstration', (audio_out(),audio_out('right')), generator=True,
        panel=ComponentPanel('Component demonstration', tuple(elements)),
    )
    # Measure first. The small gallery uses four shelf-packed columns; production
    # performances use PerformanceLayout/TabletopLayout rather than these shelves.
    sizes = [renderer.measure(e, presentation, hardware=hardware) for e in elements]
    columns = min(columns, len(elements))
    widths = [max(sizes[i][0] for i in range(c, len(elements), columns))
              for c in range(columns)]
    rows = [max(h for _, h in sizes[i:i + columns])
            for i in range(0, len(elements), columns)]
    width, height = sum(widths) + 24 * (columns + 1), sum(rows) + 24 * (len(rows) + 1) + 64
    image = Image.new('RGB', (width, height))
    renderer.background(image, theme)
    box = Rect(10, 10, width - 20, height - 20)
    group = ComponentGroup(('demo',), component.label, box, component.ports, 0, 0)
    renderer.paint_group(image, theme, group)
    renderer.text(image, theme, (28, 24), theme.name, 14, True)
    values, history = demo_signal()
    placements = []
    for i, element in enumerate(component.panel.elements):
        row, col = divmod(i, columns)
        x, y = 24 + sum(widths[:col]) + 24 * col, 64 + sum(rows[:row]) + 24 * row
        w, h = sizes[i]
        placement = DisplayPlacement(DisplayId(('demo',), element.id), component.label,
                                     element, Rect(x, y, w, h), presentation, hardware=hardware)
        assert box.contains(placement.box)
        assert all(not placement.box.overlaps(other.box) for other in placements)
        placements.append(placement)
        if isinstance(element,StereoLevelDisplay):
            renderer.stereo_levels(image,theme,placement,values,values*.3)
        elif presentation is not Presentation.STANDARD:
            renderer.compact(image, theme, placement, values)
        elif hardware:
            renderer.hardware_element(image, theme, placement)
            if element.signal is not None:
                renderer.hardware_signal(image, theme, placement, values, i)
        else:
            renderer.element(image, theme, placement)
            if element.signal is not None:
                renderer.signal(image, theme, placement, values, history, i)
    return image

# end-painting


def legacy_selector():
    from submediant.analog_face import paint_face_analog
    image = Image.new('RGB', (720, 110), '#31291e')
    draw = ImageDraw.Draw(image)
    for i, op in enumerate(('sine', 'triangle', 'square', 'sawtooth', 'noise')):
        node = {'id': 'tone', 'op': op, 'inputs': {}, 'params': {}}
        shown = paint_face_analog(draw, (8 + i * 142, 12, 136, 80), node, .6)
        assert 'op' in shown
    return image


def main(output_dir=OUTPUT):
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    factory, elements = skin_factory(), make_elements()
    assert {e.kind for e in elements} == set(DisplayKind)
    assert {e.numeric.control for e in elements if e.numeric} == set(NumericControlKind)
    assert {e.orientation for e in elements if e.kind is DisplayKind.LED_STRIP} == set(DisplayOrientation)
    from submediant.skin_model import SkinStyle
    assert {theme.style for theme in THEMES} == set(SkinStyle)
    manifest = []

    def save(name, image, **metadata):
        path = output_dir / (name + '.png')
        image.save(path)
        with Image.open(path) as reopened:
            reopened.verify()
        manifest.append(dict(file=path.name, size=image.size, **metadata))

    for theme in THEMES:
        save('skin-' + theme.id, paint_panel(factory, theme, elements), theme=theme.id)
    for element in elements:
        save('widget-' + element.id, paint_panel(factory, GUITAR, (element,)), widget=element.id)
    save('widget-mixer-fader', paint_panel(factory, MIXER, (elements[1],)))
    save('widget-drum-pad', paint_panel(factory, DRUM_MACHINE, (elements[6],)))
    controls = []
    for control in (NumericControlKind.KNOB, NumericControlKind.SLIDER):
        for label, value in (('MIN', -1), ('MID', 0), ('MAX', 1)):
            display = NumericDisplay(FixedRange(-1, 1, 2, 3).bind(value), control)
            controls.append(DisplayElement(f'{control.value}-{label.lower()}',
                f'{control.value.upper()} {label}', DisplayKind.SETTING,
                value=display.text, numeric=display))
    save('widget-control-ranges', paint_panel(factory, GUITAR, controls, columns=3))
    for presentation in Presentation:
        save('presentation-' + presentation.value,
             paint_panel(factory, GUITAR, (elements[0], elements[4]),
                         hardware=False, presentation=presentation))
    save('legacy-waveform-selector', legacy_selector())
    assert len({entry['file'] for entry in manifest}) == len(manifest)
    (output_dir / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
    print(f'Rendered {len(manifest)} component examples to {output_dir}')
    return manifest


if __name__ == '__main__':
    main()
