//
// Created by spenc on 5/21/2025.
//


#include "Texture2D.h"
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
#include <GL/glew.h>

namespace OX
{
    Texture2D::Texture2D() = default;

    Texture2D::~Texture2D()
    {
        if (m_TextureID != 0) {
            glDeleteTextures(1, &m_TextureID);
        }
    }

    bool Texture2D::LoadFromFile(const std::string &path)
    {
        stbi_set_flip_vertically_on_load(1);
        int channels;
        unsigned char *data = stbi_load(path.c_str(), &m_Width, &m_Height, &channels, 0);

        if (!data) {
            Logger::LogError("Failed to load texture: %s", path.c_str());
            return false;
        }

        GLenum format = (channels == 4) ? GL_RGBA : GL_RGB;

        glGenTextures(1, &m_TextureID);
        glBindTexture(GL_TEXTURE_2D, m_TextureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, m_Width, m_Height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        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);

        stbi_image_free(data);
        Logger::LogVerbose("Loaded texture: %s (%dx%d)", path.c_str(), m_Width, m_Height);
        return true;
    }
} // namespace OX
