#include <cstdint>
#include <pch.hpp>

#include "core.hpp"

#include <glad/glad.h>
#include <renderer/texture.hpp>
#include <opengl/opengl_texture.hpp>

#include <stb_image.h>

namespace OpenEngine {
    OpenGLTexture2D::OpenGLTexture2D(const std::string& path)
        : path(path)
    {
        int image_width, image_height, channels;
        stbi_uc* data = stbi_load(path.c_str(), &image_width, &image_height, &channels, 0);
        stbi_set_flip_vertically_on_load(1);
        OE_CORE_ASSERT(data, "Image could not be loaded!");

        width = image_width;
        height = image_height;

        GLenum internal_format, data_format = 0;
        if (channels == 4) {
            internal_format = GL_RGBA8;
            data_format = GL_RGBA;
        } else if (channels == 3) {
            internal_format = GL_RGB8;
            data_format = GL_RGB;
        }

        OE_CORE_ASSERT(internal_format & data_format, "Image format is unsupported!");

        glCreateTextures(GL_TEXTURE_2D, 1, &id);
        glTextureStorage2D(id, 1, internal_format, width, height);

        glTextureParameteri(id, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTextureParameteri(id, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        glTextureSubImage2D(id, 0, 0, 0, width, height, data_format, GL_UNSIGNED_BYTE, data);

        stbi_image_free(data);
    }

    OpenGLTexture2D::~OpenGLTexture2D()
    {
        glDeleteTextures(1, &id);
    }
    void OpenGLTexture2D::Bind(uint32_t slot) const
    {
        glBindTextureUnit(slot, id);
    }
}
