"""Simulate a moving bar and periodic illumination with row-timed exposures."""
import argparse
import json
import math
import platform
import sys
from pathlib import Path

ROWS = 1000
ROW_STEP_S = 20e-6
SPEED = 6000
MODULATION = 0.5


def motion(exposure_s, row_step_s):
    delay = (ROWS - 1) * row_step_s
    return {
        "exposure_ms": 1000 * exposure_s,
        "row_step_us": round(row_step_s * 1e6),
        "first_to_last_ms": round(delay * 1000, 6),
        "center_shift_px": round(SPEED * delay, 6),
        "motion_during_one_exposure_px": SPEED * exposure_s,
    }


def mean_light(start, duration, frequency):
    half_cycle_phase = math.pi * frequency * duration
    attenuation = math.sin(half_cycle_phase) / half_cycle_phase
    middle = start + duration / 2
    return 1 + MODULATION * attenuation * math.cos(math.tau * frequency * middle)


def light_case(frequency, exposure_s, step_s):
    values = [mean_light(row * step_s, exposure_s, frequency) for row in range(ROWS)]
    return {
        "frequency_hz": frequency,
        "exposure_ms": round(1000 * exposure_s, 6),
        "row_step_us": round(step_s * 1e6),
        "period_in_rows": round(1 / (frequency * step_s), 6) if step_s else None,
        "minimum": round(min(values), 6),
        "maximum": round(max(values), 6),
        "peak_to_peak": round(max(values) - min(values), 6),
    }


def run():
    examples = [motion(exposure, step) for exposure, step in
                ((0.0005, ROW_STEP_S), (0.005, ROW_STEP_S), (0.0005, 0), (0.0005, 5e-6))]
    assert [row["center_shift_px"] for row in examples] == [119.88, 119.88, 0, 29.97]
    assert [row["motion_during_one_exposure_px"] for row in examples] == [3, 30, 3, 3]

    lights = [light_case(freq, duration, step) for freq, duration, step in
              ((100, 0.001, ROW_STEP_S), (100, 0.010, ROW_STEP_S),
               (120, 0.010, ROW_STEP_S), (120, 1 / 120, ROW_STEP_S), (100, 0.001, 0))]
    assert lights[0]["peak_to_peak"] > 0.98
    assert lights[1]["peak_to_peak"] == lights[3]["peak_to_peak"] == lights[4]["peak_to_peak"] == 0
    assert 0.15 < lights[2]["peak_to_peak"] < 0.16
    for start in (0, 0.006, 0.01998):
        steps = 2048
        duration = 0.010
        average = sum(1 + MODULATION * math.cos(math.tau * 120 * (start + duration * (j + 0.5) / steps))
                      for j in range(steps)) / steps
        assert abs(mean_light(start, duration, 120) - average) < 1e-7
    overlap_ms = [round(1000 * max(0, time - (ROWS - 1) * ROW_STEP_S), 6)
                  for time in (0.005, 0.025)]
    assert overlap_ms == [0, 5.02]
    fps = 30
    global_frames = {
        str(freq): [round(mean_light(frame / fps, 0.001, freq), 6) for frame in range(4)]
        for freq in (100, 120)
    }
    assert global_frames["100"][0] == global_frames["100"][3]
    assert len(set(global_frames["100"])) == 3 and len(set(global_frames["120"])) == 1
    return {
        "environment": {"os": platform.system(), "os_version": platform.mac_ver()[0] or platform.release(),
                        "machine": platform.machine(), "python": sys.version.split()[0]},
        "rows": ROWS, "speed_px_per_s": SPEED, "relative_light_modulation": MODULATION,
        "motion": examples, "lighting": lights,
        "global_frames_per_second": fps,
        "global_1ms_frame_means": global_frames,
        "flash_overlap_exposure_ms": [5, 25], "all_rows_open_ms": overlap_ms,
    }


def draw_examples(path):
    from PIL import Image, ImageDraw

    image = Image.new("RGB", (936, 754), "#f4f1e9")
    draw = ImageDraw.Draw(image)
    draw.text((24, 19), "Constant-speed bar under steady light", fill="#252b31", font_size=24)
    draw.text((24, 392), "Flat field with periodically changing light", fill="#252b31", font_size=24)
    width, height = 280, 270
    motion_panels = (("Rolling / 0.5 ms", 0.0005, ROW_STEP_S),
                     ("Rolling / 5 ms", 0.005, ROW_STEP_S),
                     ("Global / 0.5 ms", 0.0005, 0))
    light_panels = (("100 Hz / 1 ms", 100, 0.001),
                    ("100 Hz / 10 ms", 100, 0.010),
                    ("120 Hz / 10 ms", 120, 0.010))
    for idx, (label, exposure, step) in enumerate(motion_panels):
        left = 24 + idx * 304
        draw.text((left, 58), label, fill="#39434e", font_size=18)
        panel = Image.new("L", (width, height))
        pixels = []
        for row in range(height):
            # Each display row samples a row in the 1000-row teaching sensor.
            time = round(row * (ROWS - 1) / (height - 1)) * step
            start, travel = 72 + SPEED * time, SPEED * exposure
            for x in range(width):
                overlap = max(0, min(start + travel, x + 9) - max(start, x - 9))
                pixels.append(round(45 + 182 * overlap / travel))
        panel.putdata(pixels)
        image.paste(panel.convert("RGB"), (left, 88))
    for idx, (label, freq, exposure) in enumerate(light_panels):
        left = 24 + idx * 304
        draw.text((left, 432), label, fill="#39434e", font_size=18)
        for row in range(height):
            time = round(row * (ROWS - 1) / (height - 1)) * ROW_STEP_S
            level = round(150 * mean_light(time, exposure, freq))
            draw.line((left, 462 + row, left + width - 1, 462 + row), fill=(level,) * 3)
    image.save(path)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--figure", type=Path, help="write the synthetic panels (requires Pillow)")
    args = parser.parse_args()
    result = run()
    if args.figure:
        draw_examples(args.figure)
    print(json.dumps(result, indent=2))
