#include "Deer/DataStore.h"
#include "DeerRender/Mesh.h"
#include "DeerRender/Mesh/Serialization/MeshDataSerialization.h"
#include "cereal/archives/json.hpp"
#include "cereal/archives/portable_binary.hpp"
#include "cereal/cereal.hpp"

namespace Deer {
	void DataStore::loadModel(MeshData& meshData, const Path& name) {
		Path realName;
		realName = Path(DEER_MESH_PATH) / (name.string() + DEER_MESH_EXTENSION);

		uint32_t size;
		uint8_t* data = DataStore::readFile(realName, &size);

		std::string strData((char*)data, size);
		std::istringstream stream(strData);

		meshData.freeData();

		{
			cereal::JSONInputArchive archive(stream);
			archive(cereal::make_nvp("mesh", meshData));
		}

		delete[] data;
	}

	void DataStore::saveModel(const MeshData& meshData, const Path& name) {
		Path realName;
		realName = Path(DEER_MESH_PATH) / (name.string() + DEER_MESH_EXTENSION);

		std::stringstream output;
		{
			cereal::JSONOutputArchive archive(output);
			archive(cereal::make_nvp("mesh", meshData));
		}
		std::string_view view = output.view();

		DataStore::saveFile(realName, (uint8_t*)view.data(), view.size());
	}

	void DataStore::saveBinModel(const MeshData& meshData, const Path& name) {
		Path realName;
		realName = Path(DEER_MESH_PATH) / (name.string() + ".dbmesh");

		std::stringstream output;
		{
			cereal::PortableBinaryOutputArchive archive(output);
			archive(cereal::make_nvp("mesh", meshData));
		}
		std::string_view view = output.view();

		DataStore::saveFile(realName, (uint8_t*)view.data(), view.size());
	}
}  // namespace Deer