#include "render.h"
#include "aliases.h"
#include "constants.h"
#include "img.h"
#include "shader.h"
#include "typed_list.h"
#include "utils.h"
#include "vec.h"
#include <math.h>

internal M4x4f g_viewport;

typedef struct triangle_bbox TriangleBBox;
struct triangle_bbox {
  u64 x0;
  u64 y0;
  u64 x1;
  u64 y1;
};

internal void render_triangle(const Triangle *triangle, const Model *model,
                              ShaderID shader, Render *render,
                              RenderType render_type, Colour colour);
internal void fill_triangle(Render *render, ShaderID shader,
                            VertexData vertices[TRIANGLE_VERTICES],
                            Colour colour, const Model *model, RenderType type);
internal TriangleBBox get_triangle_bbox(const Image *img,
                                        V2f vertices[TRIANGLE_VERTICES]);
internal V3f get_barycentric_coords(V2f a, V2f b, V2f c, V2f p);
internal V2f get_viewport_vertex(const V3f *vertex, const Image *img);

bool init_render(Arena *arena, Render *render, u64 width, u64 height) {
  render->img = (Image){.width = width, .height = height};
  if (!init_buffer(arena, &(render->img))) {
    return false;
  }

  render->depth = (Depth){.width = width, .height = height};
  if (!init_buffer(arena, &(render->depth))) {
    return false;
  }

  f32 inf = -INFINITY;
  clear_buffer(&(render->depth), &inf);

  g_viewport = viewport(0, 0, width, height);

  return true;
}

void render_model(const Model *model, Render *render, ShaderID shader,
                  RenderType render_type, Colour colour) {
  Triangle triangle;
  for (u64 i = 0; i < model->triangles->count; ++i) {
    triangle = list_get(model->triangles, i);
    render_triangle(&triangle, model, shader, render, render_type, colour);
  }
}

internal void render_triangle(const Triangle *triangle, const Model *model,
                              ShaderID shader, Render *render,
                              RenderType render_type, Colour colour) {
  Image *img = &(render->img);
  VertexData vertices[TRIANGLE_VERTICES];
  for (u64 i = 0; i < TRIANGLE_VERTICES; ++i) {
    // clang-format off
    vertices[i].position = list_get(model->vertices, triangle->positions[i]);
    vertices[i].normal = list_get(model->normals, triangle->normals[i]);
    vertices[i].uv = list_get(model->texture_coordinates, triangle->coordinates[i]);
    // clang-format on

    vertices[i] = run_vertex_shader(shader, &vertices[i], i, model);
  }

  if (render_type == RENDER_TYPE_WIREFRAME) {
    // V3f v0, v1;
    // u64 x0, y0, x1, y1;
    // for (u64 i = 0; i < TRIANGLE_VERTICES; ++i) {
    //   v0 = vertices[i];
    //   v1 = vertices[(i + 1) % TRIANGLE_VERTICES];
    //
    //   draw_line(img, (u64)v0.x, (u64)v0.y, (u64)v1.x, (u64)v1.y, colour);
    // }
  } else if (render_type == RENDER_TYPE_FILLED ||
             render_type == RENDER_TYPE_SHADED) {
    fill_triangle(render, shader, vertices, colour, model, render_type);
  }
}

internal void fill_triangle(Render *render, ShaderID shader,
                            VertexData vertices[TRIANGLE_VERTICES],
                            Colour colour, const Model *model,
                            RenderType type) {
  Image *img = &(render->img);
  Depth *depth = &(render->depth);

  V2f vp_verts[TRIANGLE_VERTICES] = {0};
  for (u64 i = 0; i < TRIANGLE_VERTICES; ++i) {
    vp_verts[i] = get_viewport_vertex(&vertices[i].position, img);
  }

  TriangleBBox bbox = get_triangle_bbox(img, vp_verts);

  V2f point;
  V3f coords;
  f32 z;
  f32 zbuf;
  FragmentResult result;

  f32 intensity = 1.0f;

  for (u64 y = bbox.y0; y <= bbox.y1; ++y) {
    for (u64 x = bbox.x0; x <= bbox.x1; ++x) {
      point = (V2f){x, y};
      coords =
          get_barycentric_coords(vp_verts[0], vp_verts[1], vp_verts[2], point);
      if (coords.x < 0.0f || coords.y < 0.0f || coords.z < 0.0f) {
        continue;
      }

      z = 0.0f;
      z += vertices[0].position.z * coords.x +
           vertices[1].position.z * coords.y +
           vertices[2].position.z * coords.z;
      zbuf = get_pixel(f32, &(render->depth), x, y);

      if (z <= zbuf) {
        continue;
      }

      result = run_fragment_shader(shader, &coords, &colour, model);
      if (DISCARD_FRAGMENT(result)) {
        continue;
      }

      set_pixel(depth, x, y, &z);
      set_pixel(img, x, y, &result.colour);
    }
  }
}

internal TriangleBBox get_triangle_bbox(const Image *img,
                                        V2f vertices[TRIANGLE_VERTICES]) {
  f32 x0 = min(vertices[0].x, min(vertices[1].x, vertices[2].x));
  f32 x1 = max(vertices[0].x, max(vertices[1].x, vertices[2].x));
  f32 y0 = min(vertices[0].y, min(vertices[1].y, vertices[2].y));
  f32 y1 = max(vertices[0].y, max(vertices[1].y, vertices[2].y));

  return (TriangleBBox){
      .x0 = x0,
      .y0 = y0,
      .x1 = x1,
      .y1 = y1,
  };
}

internal V3f get_barycentric_coords(V2f a, V2f b, V2f c, V2f p) {
  V3f x_vec = V3(V3f, f32, c.x, b.x, a.x, a.x, a.x, p.x);
  V3f y_vec = V3(V3f, f32, c.y, b.y, a.y, a.y, a.y, p.y);

  V3f u = cross_product(x_vec, y_vec);
  if (fabsf(u.z) < 1e-2) {
    return (V3f){-1.0f, 1.0f, 1.0f};
  }

  return (V3f){1.0f - (u.x + u.y) / u.z, u.y / u.z, u.x / u.z};
}

internal V2f get_viewport_vertex(const V3f *vertex, const Image *img) {
  V4f vh = {.x = vertex->x, .y = 0.0f - vertex->y, .z = vertex->z, .w = 1.0f};
  vh = mat4x4_mul_vec4(g_viewport, vh);

  V3f output = project_vec4(vh);
  output.x = clamp(output.x, 0.0f, img->width);
  output.y = clamp(output.y, 0.0f, img->height);

  return (V2f){output.x, output.y};
}
