#include "logging.hpp"
#include <pch.hpp>

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

#include <stb_image.h>
#include <cstdint>

namespace OpenEngine {
    OpenGLTexture2D::OpenGLTexture2D(uint32_t width, uint32_t height)
        : width(width), height(height)
    {
        OE_PROFILE_FUNCTION();

        internal_format = GL_RGBA8;
		data_format = GL_RGBA;

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

		glTextureParameteri(id, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTextureParameteri(id, GL_TEXTURE_WRAP_T, GL_REPEAT);
    }

    OpenGLTexture2D::OpenGLTexture2D(const std::string& path)
        : path(path)
    {
        OE_PROFILE_FUNCTION();

        int image_width, image_height, channels;
        stbi_set_flip_vertically_on_load(1);
        stbi_uc* data = stbi_load(path.c_str(), &image_width, &image_height, &channels, 0);
        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;
        }

        internal_format = _internal_format;
        data_format = _data_format;

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

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

        stbi_image_free(data);
    }

    OpenGLTexture2D::~OpenGLTexture2D()
    {
        OE_PROFILE_FUNCTION();

        glDeleteTextures(1, &id);
    }

    void OpenGLTexture2D::SetData(void* data, uint32_t size)
    {
        OE_PROFILE_FUNCTION();

        uint32_t bpp = data_format == GL_RGBA ? 4 : 3;
        OE_CORE_ASSERT(size == width * height * bpp, "Data must be entire texture!");
        glTextureSubImage2D(id, 0, 0, 0, width, height, data_format, GL_UNSIGNED_BYTE, data);
    }

    void OpenGLTexture2D::Bind(uint32_t slot) const
    {
        glBindTextureUnit(slot, id);
    }

    bool OpenGLTexture2D::operator==(const Texture& other) const
    {
        return id == other.GetID();
    }
}
