/*
 * Copyright 2015 - 2022 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#include <ox/std/buffer.hpp>

#include "read.hpp"

namespace ox {

Result<ClawHeader> readClawHeader(const char *buff, std::size_t buffLen) noexcept {
	const auto s1End = ox_strchr(buff, ';', buffLen);
	if (!s1End) {
		return OxError(1, "Could not read Claw header");
	}
	const auto s1Size = s1End - buff;
	String fmt(buff, s1Size);
	buff += s1Size + 1;
	buffLen -= s1Size + 1;

	const auto s2End = ox_strchr(buff, ';', buffLen);
	if (!s2End) {
		return OxError(2, "Could not read Claw header");
	}
	const auto s2Size = s2End - buff;
	String typeName(buff, s2Size);
	buff += s2Size + 1;
	buffLen -= s2Size + 1;

	const auto s3End = ox_strchr(buff, ';', buffLen);
	if (!s3End) {
		return OxError(3, "Could not read Claw header");
	}
	const auto s3Size = s3End - buff;
	String versionStr(buff, s3Size);
	buff += s3Size + 1;
	buffLen -= s3Size + 1;

	ClawHeader hdr;
	if (fmt == "M2") {
		hdr.fmt = ClawFormat::Metal;
	} else if (fmt == "O1") {
		hdr.fmt = ClawFormat::Organic;
	} else {
		return OxError(4, "Claw format does not match any supported format/version combo");
	}
	hdr.typeName = typeName;
	if (auto r = ox_atoi(versionStr.c_str()); r.error == 0) {
		hdr.typeVersion = r.value;
	}
	hdr.data = buff;
	hdr.dataSize = buffLen;
	return hdr;
}

Result<ClawHeader> readClawHeader(const ox::Buffer &buff) noexcept {
	return readClawHeader(buff.data(), buff.size());
}

Result<Buffer> stripClawHeader(const char *buff, std::size_t buffLen) noexcept {
	oxRequire(header, readClawHeader(buff, buffLen));
	Buffer out(header.dataSize);
	ox_memcpy(out.data(), header.data, out.size());
	return out;
}

Result<Buffer> stripClawHeader(const ox::Buffer &buff) noexcept {
	return stripClawHeader(buff.data(), buff.size());
}

Result<ModelObject> readClaw(TypeStore *ts, const Buffer &buff) noexcept {
	oxRequire(header, readClawHeader(buff));
	oxRequire(t, ts->template getLoad(header.typeName, header.typeVersion));
	ModelObject obj;
	oxReturnError(obj.setType(t));
	switch (header.fmt) {
		case ClawFormat::Metal:
		{
			MetalClawReader reader(reinterpret_cast<const uint8_t*>(header.data), header.dataSize);
			ModelHandlerInterface handler(&reader);
			oxReturnError(model(&handler, &obj));
			return obj;
		}
		case ClawFormat::Organic:
		{
#ifdef OX_USE_STDLIB
			OrganicClawReader reader(header.data, header.dataSize);
			ModelHandlerInterface handler(&reader);
			oxReturnError(model(&handler, &obj));
			return obj;
#else
			break;
#endif
		}
		case ClawFormat::None:
			return OxError(1);
	}
	return OxError(1);
}

}
