#define GL_GLEXT_PROTOTYPES
#include "engine/textures.hpp"
#include <SDL3_image/SDL_image.h>

// Texture Class Constructor
Texture::Texture(const char* filePath) {
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);

    // Load texture image
    SDL_Surface* image = IMG_Load(filePath);
    if (!image) {
        SDL_Log("Failed to load texture image.");
        return;
    }

    // Flip the image vertically
    SDL_FlipSurface(image, SDL_FLIP_VERTICAL);

    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_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    // Determine the format
    GLenum format = (image->format == SDL_PIXELFORMAT_RGBA32) ? GL_RGBA : GL_RGB;
    glTexImage2D(GL_TEXTURE_2D, 0, format, image->w, image->h, 0, format, GL_UNSIGNED_BYTE, image->pixels);
    glGenerateMipmap(GL_TEXTURE_2D);

    SDL_DestroySurface(image);
}

// Texture Class Destructor
Texture::~Texture() {
    glDeleteTextures(1, &textureID);
}

// Bind Texture Method
void Texture::bind(GLenum textureUnit) const {
    glActiveTexture(textureUnit);
    glBindTexture(GL_TEXTURE_2D, textureID);
}