/*
 * 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/.
 */

#pragma once

#include <json/json.h>

#include <ox/model/fieldcounter.hpp>
#include <ox/model/modelhandleradaptor.hpp>
#include <ox/model/optype.hpp>
#include <ox/model/types.hpp>
#include <ox/model/typenamecatcher.hpp>
#include <ox/std/buffer.hpp>
#include <ox/std/hashmap.hpp>
#include <ox/std/string.hpp>

namespace ox {

class OrganicClawWriter {

	friend Result<Buffer> writeOC(auto *val) noexcept;

	protected:
		Json::Value m_json;
		Json::ArrayIndex m_fieldIt = 0;
		int m_unionIdx = -1;

	public:
		explicit OrganicClawWriter(int unionIdx = -1) noexcept;

		explicit OrganicClawWriter(Json::Value json, int unionIdx = -1) noexcept;

		Error field(const char *key, CommonPtrWith<int8_t> auto *val) noexcept {
			if (*val) {
				value(key) = *val;
			}
			++m_fieldIt;
			return OxError(0);
		}

		Error field(const char *key, CommonPtrWith<int16_t> auto *val) noexcept {
			if (*val) {
				value(key) = *val;
			}
			++m_fieldIt;
			return OxError(0);
		}

		Error field(const char *key, CommonPtrWith<int32_t> auto *val) noexcept {
			if (*val) {
				value(key) = *val;
			}
			++m_fieldIt;
			return OxError(0);
		}

		Error field(const char *key, CommonPtrWith<int64_t> auto *val) noexcept {
			if (*val) {
				value(key) = *val;
			}
			++m_fieldIt;
			return OxError(0);
		}


		Error field(const char *key, CommonPtrWith<uint8_t> auto *val) noexcept {
			if (*val) {
				value(key) = *val;
			}
			++m_fieldIt;
			return OxError(0);
		}

		Error field(const char *key, CommonPtrWith<uint16_t> auto *val) noexcept {
			if (targetValid() && *val) {
				value(key) = *val;
			}
			++m_fieldIt;
			return OxError(0);
		}

		Error field(const char *key, CommonPtrWith<uint32_t> auto *val) noexcept {
			if (targetValid() && *val) {
				value(key) = *val;
			}
			++m_fieldIt;
			return OxError(0);
		}

		Error field(const char *key, CommonPtrWith<uint64_t> auto *val) noexcept {
			if (targetValid() && *val) {
				value(key) = *val;
			}
			++m_fieldIt;
			return OxError(0);
		}

		Error field(const char *key, CommonPtrWith<bool> auto *val) noexcept {
			if (targetValid() && *val) {
				value(key) = *val;
			}
			++m_fieldIt;
			return OxError(0);
		}

		template<typename T>
		Error field(const char*, T *val, std::size_t len) noexcept;

		template<typename U, bool force = true>
		Error field(const char*, UnionView<U, force> val) noexcept;

		template<typename T>
		Error field(const char *key, const HashMap<String, T> *val) noexcept {
			if (targetValid()) {
				const auto &keys = val->keys();
				OrganicClawWriter w;
				ModelHandlerInterface handler{&w};
				for (std::size_t i = 0; i < keys.size(); ++i) {
					const auto k = keys[i].c_str();
					if (k) [[likely]] {
						oxRequireM(value, val->at(k));
						oxReturnError(handler.field(k, value));
					}
				}
				value(key) = w.m_json;
			}
			++m_fieldIt;
			return OxError(0);
		}

		template<typename T>
		Error field(const char *key, HashMap<String, T> *val) noexcept {
			return field(key, const_cast<const HashMap<String, T>*>(val));
		}

		template<std::size_t L>
		Error field(const char *key, const BString<L> *val) noexcept {
			return field(key, SerStr(val->data(), val->cap()));
		}

		template<std::size_t L>
		Error field(const char *key, BString<L> *val) noexcept {
			return field(key, SerStr(val->data(), val->cap()));
		}

		template<std::size_t L>
		Error field(const char *key, const BasicString<L> *val) noexcept {
			if (targetValid() && val->len()) {
				value(key) = val->c_str();
			}
			++m_fieldIt;
			return OxError(0);
		}

		template<std::size_t L>
		Error field(const char *key, BasicString<L> *val) noexcept {
			return field(key, const_cast<const BasicString<L>*>(val));
		}

		Error field(const char*, SerStr val) noexcept;

		Error fieldCString(const char*, const char *const*val, int len) noexcept;

		Error fieldCString(const char *name, char **val, int len) noexcept;

		Error fieldCString(const char *name, const char *const*val) noexcept;

		Error fieldCString(const char *name, char **val) noexcept;

		template<typename T>
		Error field(const char*, T *val) noexcept;

		template<typename T = void>
		constexpr void setTypeInfo(const char* = T::TypeName, int = T::TypeVersion, int = ModelFieldCount_v<T>) noexcept {
		}

		static constexpr auto opType() noexcept {
			return OpType::Write;
		}

	private:
		[[nodiscard]]
		constexpr bool targetValid() const noexcept {
			return static_cast<int>(m_fieldIt) == m_unionIdx || m_unionIdx == -1;
		}

		[[nodiscard]]
		Json::Value &value(const char *key) noexcept;

};

template<typename T>
Error OrganicClawWriter::field(const char *key, T *val, std::size_t len) noexcept {
	if (targetValid() && len) {
		OrganicClawWriter w((Json::Value(Json::arrayValue)));
		ModelHandlerInterface handler{&w};
		for (std::size_t i = 0; i < len; ++i) {
			oxReturnError(handler.field("", &val[i]));
		}
		value(key) = w.m_json;
	}
	++m_fieldIt;
	return OxError(0);
}

template<typename T>
Error OrganicClawWriter::field(const char *key, T *val) noexcept {
	if constexpr(isVector_v<T>) {
		return field(key, val->data(), val->size());
	} else if (val && targetValid()) {
		OrganicClawWriter w;
		ModelHandlerInterface handler{&w};
		oxReturnError(model(&handler, val));
		if (!w.m_json.isNull()) {
			value(key) = w.m_json;
		}
	}
	++m_fieldIt;
	return OxError(0);
}

template<typename U, bool force>
Error OrganicClawWriter::field(const char *key, UnionView<U, force> val) noexcept {
	if (targetValid()) {
		OrganicClawWriter w(val.idx());
		ModelHandlerInterface handler{&w};
		oxReturnError(model(&handler, val.get()));
		if (!w.m_json.isNull()) {
			value(key) = w.m_json;
		}
	}
	++m_fieldIt;
	return OxError(0);
}

Result<Buffer> writeOC(auto *val) noexcept {
	OrganicClawWriter writer;
	ModelHandlerInterface handler(&writer);
	oxReturnError(model(&handler, val));
	Json::StreamWriterBuilder jsonBuilder;
	const auto str = Json::writeString(jsonBuilder, writer.m_json);
	Buffer buff(str.size() + 1);
	memcpy(buff.data(), str.c_str(), str.size() + 1);
	return buff;
}

}
