/*
 * 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 http://mozilla.org/MPL/2.0/.
 */

#pragma once

#if __has_include(<string>)
#include <string>
#endif

#if __has_include(<QString>)
#include <QString>
#endif

#include "realstd.hpp"
#include "error.hpp"
#include "bstring.hpp"
#include "string.hpp"
#include "strops.hpp"
#include "types.hpp"
#include "typetraits.hpp"

namespace ox {
namespace detail {

template<bool force = false>
constexpr StringView toStringView(const StringView &s) noexcept {
	return s;
}

template<bool force = false>
constexpr StringView toStringView(const char *s) noexcept {
	return s;
}

template<bool force = false, std::size_t size>
constexpr StringView toStringView(const BString<size> &s) noexcept {
	return s.c_str();
}

template<bool force = false, std::size_t size>
constexpr StringView toStringView(const BasicString<size> &s) noexcept {
	return s.c_str();
}

#if __has_include(<string>)
template<bool force = false>
#ifdef OX_OS_Darwin
constexpr
#else
inline
#endif
StringView toStringView(const std::string &s) noexcept {
	return s.c_str();
}
#endif

#if __has_include(<QString>)
template<bool force = false>
inline StringView toStringView(const QString &s) noexcept {
	return s.toUtf8().data();
}
#endif

template<bool force = false>
constexpr StringView toStringView(const auto&) noexcept requires(force) {
	return "<unstringable>";
}

class FmtArg {

	private:
		char dataStr[10] = {};

		template<typename T>
		static StringView sv(const T &v, char *dataStr) noexcept {
			if constexpr(is_bool_v<T>) {
				return v ? "true" : "false";
			} else if constexpr(is_integer_v<T>) {
				return ox_itoa(v, dataStr);
			} else {
				return toStringView(v);
			}
		}

	public:
		const StringView out = nullptr;

		template<typename T>
		constexpr FmtArg(const T &v) noexcept: out(sv(v, dataStr)) {
		}

};

[[nodiscard]]
constexpr uint64_t argCount(StringView str) noexcept {
	uint64_t cnt = 0;
	const auto prev = [str](std::size_t i) -> char {
		if (i > 0) {
			return str[i - 1];
		} else {
			return '\0';
		}
	};
	const auto next = [str](std::size_t i) -> char {
		if (i < str.bytes() - 1) {
			return str[i + 1];
		} else {
			return '\0';
		}
	};
	for (std::size_t i = 0; i < str.bytes(); ++i) {
		if (str[i] == '{' && prev(i) != '\\' && next(i) == '}') {
			++cnt;
		}
	}
	return cnt;
}

struct FmtSegment {
	const char *str = nullptr;
	unsigned length = 0;

	constexpr bool operator==(const FmtSegment &o) const noexcept {
		return length == o.length && ox_strncmp(str, o.str, length) == 0;
	}

	constexpr bool operator!=(const FmtSegment &o) const noexcept {
		return length != o.length || ox_strncmp(str, o.str, length) != 0;
	}
};

template<std::size_t sz>
struct Fmt {
	static constexpr std::size_t size = sz;
	ox::Array<FmtSegment, sz> segments;

	constexpr bool operator==(const Fmt<sz> &o) const noexcept {
		for (std::size_t i = 0; i < sz; ++i) {
			if (segments[i] != o.segments[i]) {
				return false;
			}
		}
		return true;
	}
};

template<std::size_t segementCnt>
[[nodiscard]]
constexpr Fmt<segementCnt> fmtSegments(StringView fmt) noexcept {
	Fmt<segementCnt> out;
	const auto prev = [fmt](std::size_t i) -> char {
		if (i > 0) {
			return fmt[i - 1];
		} else {
			return '\0';
		}
	};
	const auto next = [fmt](std::size_t i) -> char {
		if (i < fmt.bytes() - 1) {
			return fmt[i + 1];
		} else {
			return '\0';
		}
	};
	auto current = &out.segments[0];
	current->str = fmt.data();
	for (std::size_t i = 0; i < fmt.bytes(); ++i) {
		if (fmt[i] == '{' && prev(i) != '\\' && next(i) == '}') {
			++current;
			current->str = fmt.data() + i + 2;
			current->length = 0;
			i += 1;
		} else {
			++current->length;
		}
	}
	return out;
}

}

template<typename StringType = String, typename ...Args>
[[nodiscard]]
constexpr StringType sfmt(StringView fmt, Args&&... args) noexcept {
	assert(ox::detail::argCount(fmt) == sizeof...(args));
	StringType out;
	const auto fmtSegments = ox::detail::fmtSegments<sizeof...(args)+1>(fmt);
	const auto &firstSegment = fmtSegments.segments[0];
	oxIgnoreError(out.append(firstSegment.str, firstSegment.length));
	const detail::FmtArg elements[sizeof...(args)] = {args...};
	for (size_t i = 0; i < fmtSegments.size - 1; ++i) {
		out += elements[i].out;
		const auto &s = fmtSegments.segments[i + 1];
		oxIgnoreError(out.append(s.str, s.length));
	}
	return out;
}

template<typename T = String>
constexpr Result<T> join(auto d, const auto &list) {
	if (!list.size()) {
		return T("");
	}
	T out;
	out += list[0];
	for (auto i = 1ul; i < list.size(); ++i) {
		out += d;
		out += list[i];
	}
	return out;
}

}
