#include "camera.h"


void update_camera(Camera *camera) {
  Vector3 new_front = Vector3(
    cos(glm::radians(camera->yaw)) * cos(glm::radians(camera->pitch)),
    sin(glm::radians(camera->pitch)),
    sin(glm::radians(camera->yaw)) * cos(glm::radians(camera->pitch))
  );
  new_front = glm::normalize(new_front);
  camera->front = new_front;

  camera->right = glm::normalize(glm::cross(camera->front, camera->world_up));
  camera->up = glm::normalize(glm::cross(camera->right, camera->front));
}

void key_control(Camera *camera, bool *ascii_keys, f32 dt) {
  f32 velocity = camera->movement_speed * dt;

  if (ascii_keys[GLFW_KEY_W]) {
    camera->position += camera->front * velocity;
  }

  if (ascii_keys[GLFW_KEY_S]) {
    camera->position -= camera->front * velocity;
  }

  if (ascii_keys[GLFW_KEY_D]) {
    camera->position += camera->right * velocity;
  }

  if (ascii_keys[GLFW_KEY_A]) {
    camera->position -= camera->right * velocity;
  }
}

void mouse_control(Camera *camera, f32 x_change, f32 y_change) {
  x_change *= camera->rotation_speed;
  y_change *= camera->rotation_speed;

  camera->yaw += x_change;
  camera->pitch += y_change;

  // Clamp camera pitch
  if (camera->pitch > 89.0f) {
    camera->pitch = 89.0f;
  }

  if (camera->pitch < -89.0f) {
    camera->pitch = -89.0f;
  }

  update_camera(camera);
}


Matrix4 calculate_view_matrix(Camera *camera) {
  return glm::lookAt(camera->position, camera->position + camera->front, camera->up);
}

