#include "vertex_buffer.h"

bool init_vertex_buffer(Vertex_Buffer *vertex_buffer) {
  glGenVertexArrays(1, &vertex_buffer->vao);
  glGenBuffers(1, &vertex_buffer->vbo);

  glBindVertexArray(vertex_buffer->vao);
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer->vbo);

  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, position));
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, color));
  glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, uv));
  
  glEnableVertexAttribArray(0);
  glEnableVertexAttribArray(1);
  glEnableVertexAttribArray(2);

  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindVertexArray(0);

  return true;
}

void cleanup_vertex_buffer(Vertex_Buffer *vertex_buffer) {
  glDeleteBuffers(1, &vertex_buffer->vbo);
  glDeleteVertexArrays(1, &vertex_buffer->vao);
}

void upload_vertex_buffer_data(Vertex_Buffer *vertex_buffer, Mesh *vertex_data) {
  glBindVertexArray(vertex_buffer->vao);
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer->vbo);
  glBufferData(GL_ARRAY_BUFFER, vertex_data->vertices.size() * sizeof(Vertex), &vertex_data->vertices.at(0), GL_DYNAMIC_DRAW);

  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindVertexArray(0);
}

void bind_vertex_buffer(Vertex_Buffer *vertex_buffer) {
  glBindVertexArray(vertex_buffer->vao);
}

void unbind_vertex_buffer() {
  glBindVertexArray(0);
}

void draw_vertex_buffer(u32 mode, u32 start, u32 num) {
  glDrawArrays(mode, start, num);
}
