#include "client/render/loader/TextureLoader.h"

#include "client/AssetsManager.h"
#define STB_IMAGE_IMPLEMENTATION
#include "blitz/misc/Log.h"
#include "stb_image.h"
#include <glbinding/gl/gl.h>
#include <stdexcept>

using namespace gl;

namespace blitz {
namespace TextureLoader {

unsigned int LoadGLTexture(const std::string& fileName) {

	int width, height, comp;

	DataBuffer buffer = utils::AssetsManager::GetAsset(fileName.c_str());

	const unsigned char* image = stbi_load_from_memory(buffer.data(), buffer.GetSize(), &width, &height, &comp, STBI_default);

	if (image == nullptr) {
		utils::LOGE("Erreur lors du chargement de la texture !");
		throw(std::runtime_error("Failed to load texture"));
	}

	GLuint textureID;
	glGenTextures(1, &textureID);
	glBindTexture(GL_TEXTURE_2D, textureID);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	if (comp == 3)
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
	else if (comp == 4)
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);

	glBindTexture(GL_TEXTURE_2D, 0);
	stbi_image_free((void*)image);
	return textureID;
}

}  // namespace TextureLoader
}  // namespace blitz
