#define STB_IMAGE_IMPLEMENTATION
#include "texture.h"


bool load_texture(Texture *texture, string filepath) {
  texture->name = filepath;

  stbi_set_flip_vertically_on_load(true);
  u8* texture_data = stbi_load(filepath.c_str(), &texture->width, &texture->height, &texture->number_of_channels, 0);

  if (!texture_data) {
    stbi_image_free(texture_data);
    return false;
  }

  glGenTextures(1, &texture->texture);
  glBindTexture(GL_TEXTURE_2D, texture->texture);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->width, texture->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture_data);

  glGenerateMipmap(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, 0);

  stbi_image_free(texture_data);

  return true;
}

void bind_texture(Texture *texture) {
  glBindTexture(GL_TEXTURE_2D, texture->texture);
}

void unbind_texture() {
  glBindTexture(GL_TEXTURE_2D, 0);
}

void cleanup_texture(Texture *texture) {
  glDeleteTextures(1, &texture->texture);
}
