/*
 * Copyright 2016 - 2024 Gary Talent (gary@drinkingtea.net). All rights reserved.
 */

#include <keel/asset.hpp>

namespace keel {

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

ox::Result<ox::UUID> readUuidHeader(char const*buff, std::size_t buffLen) noexcept {
	if (buffLen < K1HdrSz) {
		return OxError(1, "Insufficient data to contain complete Keel header");
	}
	constexpr ox::StringView k1Hdr = "K1;";
	if (k1Hdr != ox::StringView(buff, k1Hdr.bytes())) {
		return OxError(2, "No Keel asset header data");
	}
	return ox::UUID::fromString(ox::StringView(buff + k1Hdr.bytes(), 36));
}

ox::Result<ox::ModelObject> readAsset(ox::TypeStore &ts, ox::Buffer const&buff) noexcept {
	std::size_t offset = 0;
	if (!readUuidHeader(buff).error) {
		offset = K1HdrSz;
	}
	return ox::readClaw(ts, buff.data() + offset, buff.size() - offset);
}

ox::Result<AssetHdr> readAssetHeader(char const*buff, std::size_t buffLen) noexcept {
	AssetHdr out;
	const auto err = readUuidHeader(buff, buffLen).moveTo(out.uuid);
	const auto offset = err ? 0u : K1HdrSz;
	buff = buff + offset;
	buffLen = buffLen - offset;
	oxReturnError(ox::readClawHeader(buff, buffLen).moveTo(out.clawHdr));
	return out;
}

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

}
