#include "plugin.h"

#include <gfx/asset.h>
#include <gfx/renderer.h>
#include <gfx/scene.h>
#include <gfx/util/skyquad.h>
#include <math/camera.h>
#include <math/spatial3.h>

#include <stdlib.h>

// Paths to various scene files.
static const char* BOX     = "/assets/models/box.gltf";
static const char* SUZANNE = "/assets/models/suzanne.gltf";
static const char* SPONZA =
    "/assets/glTF-Sample-Models/2.0/Sponza/glTF/Sponza.gltf";
static const char* FLIGHT_HELMET =
    "/assets/glTF-Sample-Models/2.0/FlightHelmet/glTF/FlightHelmet.gltf";
static const char* DAMAGED_HELMET =
    "/assets/glTF-Sample-Models/2.0/DamagedHelmet/glTF/DamagedHelmet.gltf";
static const char* GIRL =
    "/home/jeanne/Nextcloud/assets/models/girl/girl-with-ground.gltf";

#define DEFAULT_SCENE_FILE GIRL

struct State {
  Scene*       scene;
  Model*       model;
  SceneCamera* camera;
};

/// Load the skyquad texture.
static const Texture* load_environment_map(Gfx* gfx) {
  assert(gfx);
  return gfx_load_texture(
      gfx, &(LoadTextureCmd){
               .origin                 = AssetFromFile,
               .type                   = LoadCubemap,
               .colour_space           = sRGB,
               .filtering              = NearestFiltering,
               .mipmaps                = false,
               .data.cubemap.filepaths = {
                                          mstring_make("/assets/skybox/clouds1/clouds1_east.bmp"),
                                          mstring_make("/assets/skybox/clouds1/clouds1_west.bmp"),
                                          mstring_make("/assets/skybox/clouds1/clouds1_up.bmp"),
                                          mstring_make("/assets/skybox/clouds1/clouds1_down.bmp"),
                                          mstring_make("/assets/skybox/clouds1/clouds1_south.bmp"),
                                          mstring_make("/assets/skybox/clouds1/clouds1_north.bmp")}
  });
}

/// Load the skyquad and return the environment light node.
static SceneNode* load_skyquad(Gfx* gfx, SceneNode* root) {
  assert(gfx);
  assert(root);

  RenderBackend* render_backend = gfx_get_render_backend(gfx);

  const Texture* environment_map = load_environment_map(gfx);
  if (!environment_map) {
    return 0;
  }

  return gfx_setup_skyquad(render_backend, root, environment_map);
}

/// Load the 3D scene.
/// Return the loaded model.
static Model* load_scene(Game* game, State* state, const char* scene_filepath) {
  assert(game);
  assert(game->gfx);
  assert(state);
  assert(state->scene);

  Camera* camera = gfx_get_camera_camera(state->camera);
  spatial3_set_position(&camera->spatial, vec3_make(0, 0, 2));

  SceneNode* root           = gfx_get_scene_root(state->scene);
  SceneNode* sky_light_node = load_skyquad(game->gfx, root);
  if (!sky_light_node) {
    return 0; // test
  }

  Model* model = gfx_load_model(
      game->gfx,
      &(LoadModelCmd){
          .origin = AssetFromFile, .filepath = mstring_make(scene_filepath)});
  if (!model) {
    return 0;
  }
  SceneNode* model_node = gfx_make_model_node(model);
  if (!model_node) {
    return 0;
  }
  gfx_set_node_parent(model_node, sky_light_node);

  gfx_log_node_hierarchy(root);

  return model;
}

bool init(Game* game, State** pp_state) {
  assert(game);

  // Usage: <scene file>
  const char* scene_filepath =
      game->argc > 1 ? game->argv[1] : DEFAULT_SCENE_FILE;

  State* state = calloc(1, sizeof(State));
  if (!state) {
    goto cleanup;
  }

  if (!(state->scene = gfx_make_scene())) {
    goto cleanup;
  }
  if (!(state->camera = gfx_make_camera())) {
    goto cleanup;
  }

  state->model = load_scene(game, state, scene_filepath);
  if (!state->model) {
    goto cleanup;
  }

  Anima* anima = gfx_get_model_anima(state->model);
  if (anima) {
    gfx_play_animation(
        anima, &(AnimationPlaySettings){.name = "Walk", .loop = true});
  }

  *pp_state = state;
  return true;

cleanup:
  shutdown(game, state);
  if (state) {
    free(state);
  }
  return false;
}

void shutdown(Game* game, State* state) {
  assert(game);
  if (state) {
    gfx_destroy_camera(&state->camera);
    gfx_destroy_scene(&state->scene);
    // State freed by plugin engine.
  }
}

void update(Game* game, State* state, double t, double dt) {
  assert(game);
  assert(state);
  assert(state->scene);
  assert(state->camera);

  const vec3 orbit_point = vec3_make(0, 2, 0);
  Camera*    camera      = gfx_get_camera_camera(state->camera);
  spatial3_orbit(
      &camera->spatial, orbit_point,
      /*radius=*/5,
      /*azimuth=*/(R)(t * 0.5), /*zenith=*/0);
  spatial3_lookat(&camera->spatial, orbit_point);

  gfx_update(state->scene, state->camera, (R)t);
}

/// Render the bounding boxes of all scene objects.
static void render_bounding_boxes_rec(ImmRenderer* imm, const SceneNode* node) {
  assert(imm);
  assert(node);

  const NodeType node_type = gfx_get_node_type(node);

  if (node_type == ModelNode) {
    const Model*     model = gfx_get_node_model(node);
    const SceneNode* root  = gfx_get_model_root(model);
    render_bounding_boxes_rec(imm, root);
  } else if (node_type == ObjectNode) {
    // TODO: Look at the scene log. The JointNodes are detached from the
    //  ObjectNodes. This is why the boxes are not being transformed as expected
    //  here. Anima needs to animate boxes? Use OOBB in addition to AABB?
    //
    // TODO: Idea: when a model is loaded, compute an OOBB per joint using the
    //  vertices that are affected by the joint. Then transform this OOBB when
    //  animating the skeleton. Start with AABB for simplicity. The AABB/OOBB
    //  in the skeleton should be const. The transform AABB/OOBB is derived
    //  on demand. Stack allocator would be best for this kind of per-frame
    //  data.
    //
    // TODO: After computing joint AABB/OOBBs, check here whether the node has
    //  a skeleton, and if so, render the skeleton's boxes instead of the
    //  node's (the node's boxes are not animated, but computer from the rest
    //  pose).
    const mat4         model = gfx_get_node_global_transform(node);
    const SceneObject* obj   = gfx_get_node_object(node);
    const aabb3        box   = gfx_get_object_aabb(obj);
    gfx_imm_set_model_matrix(imm, &model);
    gfx_imm_draw_aabb3(imm, box);
  }

  // Render children's boxes.
  const SceneNode* child = gfx_get_node_child(node);
  while (child) {
    render_bounding_boxes_rec(imm, child);
    child = gfx_get_node_sibling(child);
  }
}

/// Render the bounding boxes of all scene objects.
static void render_bounding_boxes(const Game* game, const State* state) {
  assert(game);
  assert(state);

  RenderBackend* render_backend = gfx_get_render_backend(game->gfx);
  ImmRenderer*   imm            = gfx_get_imm_renderer(game->gfx);
  assert(render_backend);
  assert(imm);

  gfx_set_blending(render_backend, true);
  gfx_set_depth_mask(render_backend, false);
  gfx_set_polygon_offset(render_backend, 0.5f, 0.5f);

  gfx_imm_start(imm);
  gfx_imm_set_camera(imm, gfx_get_camera_camera(state->camera));
  gfx_imm_set_colour(imm, vec4_make(0.2, 0.2, 1.0, 0.3));
  render_bounding_boxes_rec(imm, gfx_get_scene_root(state->scene));
  gfx_imm_end(imm);

  gfx_set_polygon_offset(render_backend, 0.0f, 0.0f);
  gfx_set_depth_mask(render_backend, true);
  gfx_set_blending(render_backend, false);
}

void render(const Game* game, const State* state) {
  assert(state);
  assert(game);
  assert(game->gfx);
  assert(state->scene);
  assert(state->camera);

  Renderer* renderer = gfx_get_renderer(game->gfx);
  assert(renderer);

  gfx_render_scene(
      renderer, &(RenderSceneParams){
                    .mode   = RenderDefault,
                    .scene  = state->scene,
                    .camera = state->camera});

  render_bounding_boxes(game, state);
}

void resize(Game* game, State* state, int width, int height) {
  assert(game);
  assert(state);

  const R    fovy       = 60 * TO_RAD;
  const R    aspect     = (R)width / (R)height;
  const R    near       = 0.1;
  const R    far        = 1000;
  const mat4 projection = mat4_perspective(fovy, aspect, near, far);

  Camera* camera     = gfx_get_camera_camera(state->camera);
  camera->projection = projection;
}