"""The camera on each of its five mounts, seen from behind (system python: numpy + Pillow)
-> render/gallery/13_mount_lineup.png"""
import os
import sys

import numpy as np
from PIL import ImageDraw, ImageFont

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from render import Mesh, Camera, render, load_stl  # noqa: E402
from render_views import parts, stand_parts, M, BODY_COL, CORAL  # noqa: E402

G = os.path.normpath(os.path.join(HERE, "..", "render", "gallery"))
STEP = 115.0
MOUNT_COL = (92, 98, 108)
LINEUP = [("Desk stand", None), ("GoPro", "CoralEye_Mount_GoPro"), ("Tripod 1/4\"", "CoralEye_Mount_Tripod"),
          ("Wall", "CoralEye_Mount_Wall"), ("Magnet", "CoralEye_Mount_Magnet")]


def shifted(mesh, dx):
    return Mesh(mesh.tris + np.array([dx, 0, 0]), mesh.color * 255, mesh.spec, mesh.gloss, mesh.name)


def main():
    cam_parts = [m for m in parts(board=False) if m.name not in ("cable", "campcb", "camconn", "lens")]
    meshes = []
    for i, (label, mount) in enumerate(LINEUP):
        dx = (i - 2) * STEP
        meshes += [shifted(m, dx) for m in cam_parts]
        if mount is None:
            meshes += [shifted(m, dx) for m in stand_parts(mount_col=MOUNT_COL)]
        else:
            meshes.append(Mesh(load_stl(os.path.join(M, mount + ".stl")) + np.array([dx, 0, 0]), MOUNT_COL, 0.2, 30, mount))
    W, H = 2600, 950
    cam = Camera(eye=(32.7 + 90, 170, -820), target=(32.7, 2.0, 0.0), fov=21, width=W, height=H)
    im = render(meshes, cam, ss=2).convert("RGB")
    d = ImageDraw.Draw(im)
    try:
        f = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 40, index=1)
    except OSError:
        f = ImageFont.load_default()
    for i, (label, _) in enumerate(LINEUP):
        sx, sy, _ = cam.project(np.array([[32.7 + (i - 2) * STEP, -60.0, 0.0]]))
        tw = d.textlength(label, font=f)
        d.text((float(sx[0]) - tw / 2, H - 90), label, fill=(48, 52, 60), font=f)
    p = os.path.join(G, "13_mount_lineup.png")
    im.crop((180, 230, W - 180, H)).save(p)          # trim the empty margins
    print("saved", p)


if __name__ == "__main__":
    main()
