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

#pragma once

#include <ox/fs/fs.hpp>
#include <ox/model/typenamecatcher.hpp>
#include <ox/oc/oc.hpp>
#include <ox/std/buffer.hpp>
#include <ox/std/defines.hpp>
#include <ox/std/fmt.hpp>
#include <ox/std/trace.hpp>
#include <ox/std/string.hpp>

#include <keel/context.hpp>

namespace studio {

[[nodiscard]]
ox::String configPath(keel::Context const&ctx) noexcept;

template<typename T>
ox::Result<T> readConfig(keel::Context &ctx, ox::CRStringView name) noexcept {
	oxAssert(name != "", "Config type has no TypeName");
	const auto path = ox::sfmt("/{}.json", name);
	ox::PassThroughFS fs(configPath(ctx));
	const auto [buff, err] = fs.read(path);
	if (err) {
		oxErrf("Could not read config file: {}\n", toStr(err));
		return err;
	}
	return ox::readOC<T>(buff);
}

template<typename T>
ox::Result<T> readConfig(keel::Context &ctx) noexcept {
	constexpr auto TypeName = ox::requireModelTypeName<T>();
	return readConfig<T>(ctx, TypeName);
}

template<typename T>
ox::Error writeConfig(keel::Context &ctx, ox::CRStringView name, T *data) noexcept {
	oxAssert(name != "", "Config type has no TypeName");
	const auto path = ox::sfmt("/{}.json", name);
	ox::PassThroughFS fs(configPath(ctx));
	if (const auto err = fs.mkdir("/", true)) {
		oxErrf("Could not create config directory: {}\n", toStr(err));
		return err;
	}
	oxRequireM(buff, ox::writeOC(*data));
	*buff.back().value = '\n';
	if (const auto err = fs.write(path, buff.data(), buff.size())) {
		oxErrf("Could not read config file: {}\n", toStr(err));
		return OxError(2, "Could not read config file");
	}
	return OxError(0);
}

template<typename T>
ox::Error writeConfig(keel::Context &ctx, T *data) noexcept {
	constexpr auto TypeName = ox::requireModelTypeName<T>();
	return writeConfig(ctx, TypeName, data);
}

template<typename T, typename Func>
void openConfig(keel::Context &ctx, ox::CRStringView name, Func f) noexcept {
	oxAssert(name != "", "Config type has no TypeName");
	const auto [c, err] = readConfig<T>(ctx, name);
	oxLogError(err);
	f(&c);
}

template<typename T, typename Func>
void openConfig(keel::Context &ctx, Func f) noexcept {
	constexpr auto TypeName = ox::requireModelTypeName<T>();
	openConfig<T>(ctx, TypeName, f);
}

template<typename T, typename Func>
void editConfig(keel::Context &ctx, ox::CRStringView name, Func f) noexcept {
	oxAssert(name !=  "", "Config type has no TypeName");
	auto [c, err] = readConfig<T>(ctx, name);
	oxLogError(err);
	f(&c);
	oxLogError(writeConfig(ctx, name, &c));
}

template<typename T, typename Func>
void editConfig(keel::Context &ctx, Func f) noexcept {
	constexpr auto TypeName = ox::requireModelTypeName<T>();
	editConfig<T>(ctx, TypeName, f);
}

}
