#include "texture.h"


Texture::~Texture() {
  clear_texture(this);
}

bool load_texture(Texture *texture) {
  u8 *texture_data = stbi_load(texture->file_path, &texture->width, &texture->height, &texture->bit_depth, 0);

  if (!texture_data) {
    printf("Failed to find: %s\n", texture->file_path);
    return false;
  }

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

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

  // Maybe just set to GL_RGB
  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 use_texture(Texture *texture) {
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, texture->id);  
}

void clear_texture(Texture *texture) {
  glDeleteTextures(1, &texture->id);
  texture->id = 0;
  texture->width = 0;
  texture->height = 0;
  texture->bit_depth = 0;
  texture->file_path = nullptr;
}

