#include "DeerRender/Log.h"
#include "DeerRender/Texture.h"
#include "DeerStudio/EditorDataImporter.h"
#include "stb_image.h"

#include <cstring>

namespace Deer {
	template <>
	Scope<TextureData> StorageData::deserialize<EditorDataImporter, TextureData>() {
		stbi_set_flip_vertically_on_load(true);
		int width, height, channels;

		stbi_uc* data = stbi_load_from_memory(getData(), size, &width, &height, &channels, 0);

		if (!data) {
			DEER_CORE_ERROR("Error loading {}", getMetadata()["storageId"].c_str());
			return nullptr;
		}

		TextureFormat format = NONE;
		switch (channels) {
		case 4:
			format = RGBA8;
			break;
		case 3:
			format = RGB8;
			break;
		case 1:
			format = R8;
			break;
		default:
			DEER_CORE_ERROR("Error loading {}, invalid chanel count {}", getMetadata()["storageId"].c_str(), channels);
			return nullptr;
		}

		Scope<TextureData> textureData = MakeScope<TextureData>(format, width, height);
		std::memcpy(textureData->getData(), data, textureData->getSize());
		stbi_image_free(data);

		return textureData;
	}
} // namespace Deer