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

#pragma once

#include <ox/fs/fs.hpp>
#include <ox/preloader/preloader.hpp>

#include "asset.hpp"
#include "media.hpp"

namespace keel {

class Context;

struct GbaPlatSpec {
	using PtrType = uint32_t;
	using size_t = uint32_t;

	static constexpr PtrType RomStart = 0x08000000;

	[[nodiscard]]
	static constexpr std::size_t alignOf(const bool) noexcept {
		return 1;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(const uint8_t) noexcept {
		return 1;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(const uint16_t) noexcept {
		return 2;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(const uint32_t) noexcept {
		return 4;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(const uint64_t) noexcept {
		return 8;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(const int8_t)  noexcept {
		return 1;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(const int16_t) noexcept {
		return 2;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(const int32_t) noexcept {
		return 4;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(const int64_t) noexcept {
		return 8;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(auto const*) noexcept {
		return 4;
	}

	[[nodiscard]]
	static constexpr auto correctEndianness(auto v) noexcept {
		return ox::toLittleEndian(v);
	}

};

using GbaPreloader = ox::Preloader<GbaPlatSpec>;

namespace detail {
// transformations need to be done after the copy to the new FS is complete
template<typename PlatSpec>
ox::Error preloadObj(
		ox::TypeStore &ts,
		ox::FileSystem &romFs,
		ox::Preloader<PlatSpec> &pl,
		ox::CRStringView path) noexcept {
	// load file
	oxRequireM(buff, romFs.read(path));
	oxRequireM(obj, keel::readAsset(ts, buff));
	if (obj.type()->preloadable) {
		oxOutf("preloading {} as a {}\n", path, obj.type()->typeName);
		// preload
		oxRequire(a, pl.startAlloc(ox::sizeOf<GbaPlatSpec>(&obj), ox::alignOf<GbaPlatSpec>(obj)));
		auto const err = ox::preload<GbaPlatSpec, decltype(obj)>(&pl, &obj);
		oxReturnError(pl.endAlloc());
		oxReturnError(err);
		keel::PreloadPtr const p{.preloadAddr = static_cast<uint32_t>(a)};
		oxReturnError(ox::writeMC(p).moveTo(buff));
	} else {
		// strip the Claw header (it is not needed after preloading) and write back out to dest fs
		oxReturnError(ox::writeMC(obj).moveTo(buff));
	}
	oxReturnError(romFs.write(path, buff.data(), buff.size()));
	return {};
}

// claw file transformations are broken out because path to inode
// transformations need to be done after the copy to the new FS is complete
template<typename PlatSpec>
ox::Error preloadDir(
		ox::TypeStore &ts,
		ox::FileSystem &romFs,
		ox::Preloader<PlatSpec> &pl,
		ox::CRStringView path) noexcept {
	// copy
	oxTracef("pack.preload", "path: {}", path);
	oxRequire(fileList, romFs.ls(path));
	for (auto const&name : fileList) {
		auto const filePath = ox::sfmt("{}{}", path, name);
		oxRequire(stat, romFs.stat(filePath));
		if (stat.fileType == ox::FileType::Directory) {
			auto const dir = ox::sfmt("{}{}/", path, name);
			oxReturnError(preloadDir(ts, romFs, pl, dir));
		} else {
			auto const err = preloadObj(ts, romFs, pl, filePath);
			if (err) {
				oxErrf("\033[31;1;1mCould not preload {}:\n\t{}\n", filePath, toStr(err));
				return err;
			}
		}
	}
	return {};
}

}

template<typename PlatSpec>
ox::Error appendBinary(ox::Buffer &binBuff, ox::SpanView<char> const&fsBuff, ox::Preloader<PlatSpec> &pl) noexcept {
	constexpr auto padbin = [](ox::BufferWriter &w, unsigned factor) noexcept -> ox::Error {
		return w.write(nullptr, factor - w.buff().size() % factor);
	};
	constexpr ox::StringView mediaHdr   = "KEEL_MEDIA_HEADER_______________";
	constexpr ox::StringView preloadHdr = "KEEL_PRELOAD_HEADER_____________";
	constexpr auto hdrSize = 32u;
	static_assert(mediaHdr.bytes() == hdrSize);
	static_assert(preloadHdr.bytes() == hdrSize);
	ox::BufferWriter w(&binBuff);
	oxReturnError(padbin(w, hdrSize));
	oxReturnError(w.write(mediaHdr.data(), mediaHdr.bytes()));
	oxReturnError(w.write(fsBuff.data(), fsBuff.size()));
	oxReturnError(padbin(w, hdrSize));
	oxReturnError(w.write(preloadHdr.data(), preloadHdr.bytes()));
	oxReturnError(pl.offsetPtrs(binBuff.size()));
	auto const&plBuff = pl.buff();
	oxReturnError(w.write(plBuff.data(), plBuff.size()));
	return {};
}

template<typename PlatSpec>
ox::Error preload(ox::TypeStore &ts, ox::FileSystem &src, ox::Preloader<PlatSpec> &pl) noexcept {
	oxOut("Preloading\n");
	return detail::preloadDir(ts, src, pl, "/");
}

ox::Error pack(keel::Context &ctx, ox::TypeStore &ts, ox::FileSystem &dest) noexcept;

}
