"""Render isolated Foley from the frame cues in edit.json, using Python's standard library."""
import array
import json
import math
from pathlib import Path
import random
import wave

ROOT = Path(__file__).resolve().parent
RATE = 48000
# Contact resonances (frequency, relative level and decay in seconds).
MATERIALS = {
    "rocker": [(232, .36, .022), (710, .23, .012), (1820, .14, .009)],
    "key": [(315, .25, .016), (930, .19, .016), (2360, .09, .012)],
    "relay": [(172, .27, .028), (840, .20, .014), (3170, .10, .014)],
    "cup": [(358, .13, .044), (790, .16, .083), (1927, .22, .12), (3091, .06, .073)],
    "tray": [(210, .22, .034), (603, .18, .038), (1609, .08, .052)],
    "water": [(1870, .18, .014), (2810, .18, .019), (4410, .07, .013)],
}


def contact(kind, rng):
    span = .53 if kind == "cup" else .2
    length = int(span * RATE)
    raw = array.array("f", [0]) * length
    grain, pitch = 0.0, rng.uniform(.94, 1.05)
    for i in range(length):
        time = i / RATE
        sample = rng.uniform(-1, 1)
        grain = grain * .62 + .38 * sample
        attack = min(1.0, time * 5200)
        noise = (sample - grain) * .34 * math.exp(-time / .0048)
        body = sum(level * math.sin(2*math.pi*freq*pitch*time) * math.exp(-time/decay)
                   for freq, level, decay in MATERIALS[kind])
        raw[i] = (body + noise) * attack
    return raw


def render(edit, path):
    starts, end = {}, 0
    for shot in edit["shots"]:
        starts[shot["id"]] = end
        end += shot["frames"]
    track = array.array("f", [0]) * round(RATE * end / edit["fps"])
    for i, cue in enumerate(edit["sound"]["foley"]):
        start = round(RATE * (starts[cue["shot"]] + cue["frame"]) / edit["fps"])
        if cue["frame"] < 0 or start >= len(track):
            raise ValueError("Foley cue falls outside the edit")
        rng = random.Random(2319 + i)
        hit = contact(cue["kind"], rng)
        gain = 10 ** (cue["gainDb"] / 20)
        impacts = [(0, 1), (.013, .11), (.029, .065), (.052, .035)]
        if cue["kind"] in ("rocker", "relay"):
            impacts.append((.008, .19))
        for delay, level in impacts:
            offset = start + round(RATE * delay)
            for j in range(min(len(hit), len(track) - offset)):
                track[offset + j] += hit[j] * gain * level
    pcm = array.array("h", (round(max(-1, min(1, v)) * 32767) for v in track))
    with wave.open(str(path), "wb") as wav:
        wav.setparams((1, 2, RATE, len(pcm), "NONE", "not compressed"))
        wav.writeframes(pcm.tobytes())


if __name__ == "__main__":
    render(json.loads((ROOT / "edit.json").read_text()), ROOT / "foley.wav")
