#include "obj.h"
#include "aliases.h"
#include "img.h"
#include "mem_arena.h"
#include "pam.h"
#include "typed_list.h"
#include "utils.h"
#include "vec.h"
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TRIANGLE_VERTICES 3

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,
                              const Shader *shader, Render *render,
                              RenderType render_type, Colour colour);
internal void fill_triangle(Render *render, V3f vertices[TRIANGLE_VERTICES],
                            V3f normals[TRIANGLE_VERTICES],
                            V2f coordinates[TRIANGLE_VERTICES], Colour colour,
                            Image *texture, RenderType type);
internal TriangleBBox get_triangle_bbox(const Image *img,
                                        V3f vertices[TRIANGLE_VERTICES]);
internal V3f get_barycentric_coords(f32 d00, f32 d01, f32 d11, f32 denom,
                                    const V2i *ab, const V2i *ac,
                                    const V2i *ap);
internal V3f get_viewport_vertex(const V3f *vertex, const Image *img);

V3f g_light_dir = {0.0f, 0.0f, 1.0f};

Model load_obj_file(Arena *arena, const char *filename, const char *texture) {
  if (!arena) {
    return INVALID_MODEL;
  }

  FILE *fp = fopen(filename, "r");
  if (!fp) {
    return INVALID_MODEL;
  }

  Model model = (Model){
      .vertices = list_create(V3f, arena),
      .normals = list_create(V3f, arena),
      .texture_coordinates = list_create(V2f, arena),
      .triangles = list_create(Triangle, arena),
  };
  if (!(model.vertices) || !(model.normals) || !(model.texture_coordinates) ||
      !(model.triangles)) {
    return INVALID_MODEL;
  }

  char line[8192];
  char identifier[8];
  V3f vertex;
  V3f normal;
  V2f coord;
  Triangle triangle;
  f32 vx, vy, vz;
  f32 nx, ny, nz;
  f32 u, v;
  u64 fp0, fp1, fp2;
  u64 vn0, vn1, vn2;
  u64 tx0, tx1, tx2;
  while (fgets(line, 8191, fp) != NULL) {
    sscanf(line, "%s", identifier);
    if (strncmp(identifier, "v", 8) == 0) {
      sscanf(line + 2, "%f %f %f", &vx, &vy, &vz);
      vertex.x = vx;
      vertex.y = vy;
      vertex.z = vz;
      list_append(V3f, arena, model.vertices, vertex);
    } else if (strncmp(identifier, "vn", 8) == 0) {
      sscanf(line + 2, "%f %f %f", &nx, &ny, &nz);
      normal.x = nx;
      normal.y = ny;
      normal.z = nz;
      list_append(V3f, arena, model.normals, normal);
    } else if (strncmp(identifier, "vt", 8) == 0) {
      sscanf(line + 2, "%f %f", &u, &v);
      coord.u = u;
      coord.v = v;
      list_append(V2f, arena, model.texture_coordinates, coord);
    } else if (strncmp(identifier, "f", 8) == 0) {
      sscanf(line + 2, "%lu/%lu/%lu %lu/%lu/%lu %lu/%lu/%lu", &fp0, &tx0, &vn0,
             &fp1, &tx1, &vn1, &fp2, &tx2, &vn2);
      // OBJ indices start from 1
      triangle.p0 = fp0 - 1;
      triangle.p1 = fp1 - 1;
      triangle.p2 = fp2 - 1;
      triangle.n0 = vn0 - 1;
      triangle.n1 = vn1 - 1;
      triangle.n2 = vn2 - 1;
      triangle.tx0 = tx0 - 1;
      triangle.tx1 = tx1 - 1;
      triangle.tx2 = tx2 - 1;
      list_append(Triangle, arena, model.triangles, triangle);
    }
  }

  if (texture) {
    model.texture = load_p6_image(arena, texture);
  }

  return model;
}

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);

  return true;
}

void render_model(const Model *model, Render *render, const Shader *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,
                              const Shader *shader, Render *render,
                              RenderType render_type, Colour colour) {
  Image *img = &(render->img);
  V3f vertices[TRIANGLE_VERTICES] = {
      list_get(model->vertices, triangle->p0),
      list_get(model->vertices, triangle->p1),
      list_get(model->vertices, triangle->p2),
  };
  V3f normals[TRIANGLE_VERTICES] = {
      list_get(model->normals, triangle->n0),
      list_get(model->normals, triangle->n1),
      list_get(model->normals, triangle->n2),
  };
  V2f coordinates[TRIANGLE_VERTICES] = {
      list_get(model->texture_coordinates, triangle->tx0),
      list_get(model->texture_coordinates, triangle->tx1),
      list_get(model->texture_coordinates, triangle->tx2),
  };

  for (u64 i = 0; i < TRIANGLE_VERTICES; ++i) {
    vertices[i] = shader->vertex(&vertices[i], shader->model_view,
                                 shader->projection, &render->img);
  }

  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, vertices, normals, coordinates, colour,
                  model->texture, render_type);
  }
}

internal void fill_triangle(Render *render, V3f vertices[TRIANGLE_VERTICES],
                            V3f normals[TRIANGLE_VERTICES],
                            V2f coordinates[TRIANGLE_VERTICES], Colour colour,
                            Image *texture, RenderType type) {
  Image *img = &(render->img);
  Depth *depth = &(render->depth);
  TriangleBBox bbox = get_triangle_bbox(img, vertices);

  V3f v0 = vertices[0];
  V3f v1 = vertices[1];
  V3f v2 = vertices[2];

  V2i ab = V2(V2i, i64, v0.x, v0.y, v1.x, v1.y);
  V2i ac = V2(V2i, i64, v0.x, v0.y, v2.x, v2.y);
  f32 d00 = dot_v2(ab, ab);
  f32 d01 = dot_v2(ab, ac);
  f32 d11 = dot_v2(ac, ac);
  f32 denom = d00 * d11 - d01 * d01;
  V2i ap;
  V3f coords;
  f32 z;
  f32 zbuf;
  f32 nx, ny, nz;
  V3f normal;
  f32 tx_u, tx_v;
  u64 tx_x, tx_y;

  f32 intensity = 1.0f;

  for (u64 y = bbox.y0; y <= bbox.y1; ++y) {
    for (u64 x = bbox.x0; x <= bbox.x1; ++x) {
      ap = V2(V2i, i64, v0.x, v0.y, x, y);
      coords = get_barycentric_coords(d00, d01, d11, denom, &ab, &ac, &ap);
      if (coords.x < 0.0f || coords.y < 0.0f || coords.x + coords.y > 1.0f) {
        continue;
      }

      z = 0.0f;
      z += v0.z * coords.x + v1.z * coords.y + v2.z * coords.z;
      zbuf = get_pixel(f32, &(render->depth), x, y);

      if (z > zbuf) {
        if (type == RENDER_TYPE_SHADED) {
          nx = normals[0].x * coords.x + normals[1].x * coords.y +
               normals[2].x * coords.z;
          ny = normals[0].y * coords.x + normals[1].y * coords.y +
               normals[2].y * coords.z;
          nz = normals[0].z * coords.x + normals[1].z * coords.y +
               normals[2].z * coords.z;
          normal = (V3f){nx, ny, nz};
          intensity = dot_v3(normal, g_light_dir);
        }

        if (intensity < 0.0f) {
          intensity = 0.01f;
        }

        if (texture) {
          tx_u = coordinates[0].u * coords.x + coordinates[1].u * coords.y +
                 coordinates[2].u * coords.z;
          tx_v = coordinates[0].v * coords.x + coordinates[1].v * coords.y +
                 coordinates[2].v * coords.z;
          tx_x = tx_u * texture->width;
          tx_y = (1.0f - tx_v) * texture->height;

          colour = get_pixel(Colour, texture, tx_x, tx_y);
        }

        colour.r *= intensity;
        colour.g *= intensity;
        colour.b *= intensity;

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

internal TriangleBBox get_triangle_bbox(const Image *img,
                                        V3f 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(f32 d00, f32 d01, f32 d11, f32 denom,
                                    const V2i *ab, const V2i *ac,
                                    const V2i *ap) {
  if (denom == 0.0f) {
    return (V3f){-INFINITY, -INFINITY, -INFINITY};
  }

  f32 d20 = dot_v2((*ap), (*ab));
  f32 d21 = dot_v2((*ap), (*ac));

  f32 v = (d11 * d20 - d01 * d21) / denom;
  f32 w = (d00 * d21 - d01 * d20) / denom;
  f32 u = 1.0f - v - w;

  return (V3f){v, w, u};
}

internal V3f 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(viewport(vh.x, vh.y, img->width, img->height), vh);
  return project_vec4(vh);
}
