"""Run with: python -m starter.assignment --section all"""

import argparse
import json
import time
from pathlib import Path

import imageio.v2 as imageio
import numpy as np
import torch
from PIL import Image, ImageDraw
from pytorch3d.renderer import FoVPerspectiveCameras, PointLights, look_at_view_transform
from pytorch3d.structures import Meshes

from starter.camera_transforms import TRANSFORMS, render_textured_cow
from starter.dolly_zoom import dolly_zoom
from starter.geometry import (
    cube, gradient_colors, implicit_mesh, mesh, parametric_points,
    point_cloud, sample_surface, snowman, tetrahedron,
)
from starter.render_generic import load_rgbd_data
from starter.utils import get_mesh_renderer, get_points_renderer, load_cow_mesh, unproject_depth_image


def camera(azimuth, distance=4, elevation=20, target=(0, 0, 0), up=(0, 1, 0)):
    rotation, translation = look_at_view_transform(
        distance, elevation, azimuth, at=(target,), up=(up,)
    )
    return FoVPerspectiveCameras(R=rotation, T=translation, znear=0.01)


def rgb_image(render):
    return (render[0, ..., :3].cpu().numpy().clip(0, 1) * 255).astype(np.uint8)


def save_gif(path, frames):
    # GIF durations are multiples of 10 ms; alternate them to average 15 fps.
    durations = np.diff(np.round(np.arange(len(frames) + 1) * 100 / 15)) * 10
    imageio.mimsave(path, frames, duration=durations.tolist(), loop=0)


def comparison(frames, labels):
    width, height = frames[0].shape[1], frames[0].shape[0]
    panel = Image.new("RGB", (width * len(frames), height + 26), "white")
    draw = ImageDraw.Draw(panel)
    for i, (frame, label) in enumerate(zip(frames, labels)):
        panel.paste(Image.fromarray(frame), (i * width, 26))
        draw.text((i * width + 8, 7), label, fill="black")
    return np.asarray(panel)


@torch.no_grad()
def run(args):
    torch.set_num_threads(4)
    torch.manual_seed(7)
    output = Path(args.output_dir)
    output.mkdir(parents=True, exist_ok=True)
    timing_path = output / "timings.json"
    timings = json.loads(timing_path.read_text()) if timing_path.exists() else {}
    mesh_renderer = get_mesh_renderer(args.image_size, device="cpu")
    points_renderer = get_points_renderer(args.image_size, device="cpu", radius=0.012)

    def wanted(section):
        return args.section in ("all", section, section.split(".")[0])

    def render_object(obj, view):
        if isinstance(obj, Meshes):
            lights = PointLights(location=view.get_camera_center())
            return rgb_image(mesh_renderer(obj, cameras=view, lights=lights))
        return rgb_image(points_renderer(obj, cameras=view))

    def turntable(name, objects, labels=None, distance=4, elevation=20, target=(0, 0, 0), up=(0, 1, 0)):
        print(f"Rendering {name} ...", flush=True)
        start = time.perf_counter()
        frames = []
        individual = [[] for _ in objects]
        for index, azimuth in enumerate(np.linspace(180, 540, args.num_frames, endpoint=False)):
            view = camera(float(azimuth), distance, elevation, target, up)
            images = [render_object(obj, view) for obj in objects]
            for sequence, frame in zip(individual, images):
                sequence.append(frame)
            frames.append(comparison(images, labels) if labels else images[0])
            if (index + 1) % 15 == 0:
                print(f"  {index + 1}/{args.num_frames} frames", flush=True)
        seconds = time.perf_counter() - start
        save_gif(output / f"{name}.gif", frames)
        if name == "rgbd":
            for i, sequence in enumerate(individual):
                save_gif(output / f"rgbd_{i + 1}.gif", sequence)
        timings[name] = {
            "render_seconds": round(seconds, 3), "frames": args.num_frames,
            "image_size": args.image_size,
            "objects": [{"kind": "mesh", "vertices": len(obj.verts_packed()),
                         "faces": len(obj.faces_packed())} if isinstance(obj, Meshes)
                        else {"kind": "points", "points": len(obj.points_packed())}
                        for obj in objects],
        }
        timing_path.write_text(json.dumps(timings, indent=2) + "\n")
        print(f"  {seconds:.1f}s ({seconds / args.num_frames:.3f}s/frame)", flush=True)

    vertices, faces = load_cow_mesh()
    cow = mesh(vertices, faces)
    if wanted("1"):
        turntable("cow", [cow])
        start = time.perf_counter()
        dolly_zoom(args.image_size, args.num_frames, args.num_frames / 15,
                   device="cpu", output_file=str(output / "dolly.gif"))
        timings["dolly"] = {"total_seconds": round(time.perf_counter() - start, 3),
                            "frames": args.num_frames, "image_size": args.image_size}
        timing_path.write_text(json.dumps(timings, indent=2) + "\n")
    if wanted("2"):
        turntable("tetrahedron", [tetrahedron()])
        turntable("cube", [cube()])
    if wanted("3"):
        turntable("retextured", [mesh(vertices, faces, gradient_colors(vertices))])
    if wanted("4"):
        base = render_textured_cow(image_size=args.image_size, device="cpu")
        imageio.imwrite(output / "camera_base.png", (base.clip(0, 1) * 255).astype(np.uint8))
        for name, (rotation, translation) in TRANSFORMS.items():
            result = render_textured_cow(image_size=args.image_size, R_relative=rotation,
                                        T_relative=translation, device="cpu")
            imageio.imwrite(output / f"camera_{name}.png", (result.clip(0, 1) * 255).astype(np.uint8))
    if wanted("5.1"):
        data = load_rgbd_data()
        clouds = []
        for i in (1, 2):
            points, colors = unproject_depth_image(
                torch.as_tensor(data[f"rgb{i}"]), torch.as_tensor(data[f"mask{i}"]),
                torch.as_tensor(data[f"depth{i}"]), data[f"cameras{i}"]
            )
            clouds.append(point_cloud(points[::args.point_stride], colors[::args.point_stride]))
        points = torch.cat([cloud.points_packed() for cloud in clouds])
        colors = torch.cat([cloud.features_packed() for cloud in clouds])
        clouds.append(point_cloud(points, colors))
        turntable("rgbd", clouds, ["View 1", "View 2", "Union"], distance=6,
                  elevation=-10, up=(0, -1, 0))
    if wanted("5.2"):
        for shape in ("torus", "ellipsoid"):
            turntable(f"{shape}_points", [point_cloud(parametric_points(shape))], elevation=30)
    if wanted("5.3"):
        for shape in ("torus", "ellipsoid"):
            turntable(f"{shape}_mesh", [implicit_mesh(shape)], elevation=30)
    if wanted("6"):
        turntable("snowman", [snowman()], distance=6, elevation=10, target=(0, 0.25, 0))
    if wanted("7"):
        counts = [10, 100, 1000, 10000]
        clouds = [sample_surface(cow, count) for count in counts]
        turntable("sampling", [*clouds, cow], [*map(str, counts), "Mesh"])


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--section", default="all",
                        choices=["all", "1", "2", "3", "4", "5", "5.1", "5.2", "5.3", "6", "7"])
    parser.add_argument("--image_size", type=int, default=256)
    parser.add_argument("--num_frames", type=int, default=60)
    parser.add_argument("--point_stride", type=int, default=8,
                        help="Render every nth RGB-D point; use 1 for all points.")
    parser.add_argument("--output_dir", default="assets")
    args = parser.parse_args()
    if args.image_size < 16 or args.num_frames < 2 or args.point_stride < 1:
        parser.error("Use image_size >= 16, num_frames >= 2, and point_stride >= 1.")
    run(args)


if __name__ == "__main__":
    main()
