// =====================================================================================================================
//  fennec, a free and open source game engine
//  Copyright © 2025 - 2026  Medusa Slockbower
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <https://www.gnu.org/licenses/>.
// =====================================================================================================================

#ifndef FENNEC_STRING_WSTRING_H
#define FENNEC_STRING_WSTRING_H

#include <fennec/string/detail/_ctype.h>

#include <fennec/string/wcstring.h>
#include <fennec/string/string_view.h>

#include <fennec/memory/allocator.h>
#include <fennec/memory/common.h>

#include <fennec/math/common.h>

namespace fennec
{

// Forward def
template<typename AllocT = allocator<wchar_t>> struct _wstring;

// Alias for default allocator
using wstring = _wstring<>;

///
/// \brief Struct for wrapping c-style strings
///
/// \details behaviour guarantees that the underlying string is null-terminated
template<typename AllocT>
struct _wstring
{
// Definitions =========================================================================================================
public:

	/// \name Constants
	/// @{

	static constexpr size_t npos = -1; //!< Constant representing a null position in the string.

	/// @}


	/// \name Definitions
	/// @{

	using char_t = wchar_t;                      //!< the character type
	using alloc_t = allocation<wchar_t, AllocT>; //!< the allocator type

	/// @}


// Constructors & Destructor ===========================================================================================

	/// \name Constructors & Destructor
	/// @{

	///
	/// \brief Default Constructor, initializes empty string
	constexpr _wstring()
		: _str() {
	}

	///
	/// \brief Sized Constructor, initializes a null-terminated string of size \emph{n} with `'c'...`
	/// \param n the number of characters
	/// \param c the character to fill with
	///
	/// \details Adds additional character for null termination.
	constexpr _wstring(size_t n, wchar_t c = '\0')
		: _str(n + 1) {
		fennec::memset(_str, c, n);
	}

	///
	/// \brief Alloc Constructor
	/// \param alloc The allocator to use
	constexpr _wstring(const alloc_t& alloc)
		: _str(alloc) {
	}

	///
	/// \brief Sized Alloc Constructor, initializes a null-terminated string of size \emph{n} with `'c'...`
	/// \param n the number of characters
	/// \param c the character to fill with
	/// \param alloc The allocator to use
	///
	/// \details Adds additional character for null termination.
	constexpr _wstring(size_t n, wchar_t c, const alloc_t& alloc)
		: _str(n + 1, alloc) {
		fennec::memset(_str, c, n);
	}

	///
	/// \brief C-String Constructor
	/// \param cstr The C-Style string to construct from.
	constexpr _wstring(const wcstring& cstr)
		: _str(cstr, cstr.size() + 1) {
	}

	///
	/// \brief Buffer Constructor, wraps the provided C-Style string, appending a null-terminator if not present
	/// \param str the buffer to wrap
	/// \tparam n the number of characters in the buffer including the null-terminator, if present
	///
	/// \details This constructor is explicit because we want to be explicit about when we are allocating memory for
	///          a string.
	template<size_t n>
	explicit constexpr _wstring(const wchar_t (&str)[n])
		: _str(str[n - 1] != '\0' ? n + 1 : n) {
		fennec::memcpy(_str, str, n);
		if (str[n - 1] != '\0') {
			_str[n] = '\0';
		}
	}

	///
	/// \brief Buffer Constructor, wraps the provided C-Style string, appending a null-terminator if not present
	/// \param buf the buffer to wrap
	/// \param n the number of characters in the buffer including the null-terminator, if present
	constexpr _wstring(const wchar_t* buf, size_t n)
		: _str(buf[n - 1] != '\0' ? n + 1 : n) {
		fennec::memcpy(_str, buf, n);
		if (buf[n - 1] != '\0') {
			_str[n] = '\0';
		}
	}

	///
	/// \brief String View Constructor
	/// \param view The C-Style string view to construct from.
	constexpr _wstring(const string_view& view)
		: _wstring(view.str, view.len) {
	}

	///
	/// \brief String Copy Constructor
	/// \param str the string to copy
	constexpr _wstring(const _wstring& str) = default;

	///
	/// \brief String Move Constructor
	/// \param str the string to take ownership of
	constexpr _wstring(_wstring&& str) noexcept = default;

	///
	/// \brief  Destructor, cleans up underlying allocation
	constexpr ~_wstring() = default;

	/// @}


// Assignment ==========================================================================================================
public:

	/// \name Assignment
	/// @{

	///
	/// \brief C-String Assignment
	/// \param cstr The C-Style string to assign.
	/// \returns A reference to \emph{this}
	constexpr _wstring& operator=(const wcstring& cstr) {
		_str.allocate(cstr.capacity());
		fennec::memcpy(_str, cstr, cstr.capacity());
		return *this;
	}

	///
	/// \brief String Copy Assignment
	/// \param str the string to copy
	/// \returns A reference to \emph{this}
	constexpr _wstring& operator=(const _wstring& str) {
		_str = str._str;
		return *this;
	}

	///
	/// \brief String Move Assignment
	/// \param str the string to take ownership of
	/// \returns A reference to \emph{this}
	constexpr _wstring& operator=(_wstring&& str) noexcept {
		_str = fennec::move(str._str);
		return *this;
	}

	/// @}


// Properties ==========================================================================================================
public:

	/// \name Properties
	/// @{

	///
	/// \returns The size of the string excluding null terminator
	constexpr size_t size() const {
		return _str.capacity() > 0 ? _str.capacity() - 1 : 0;
	}

	///
	/// \returns The size of the string including null terminator
	constexpr size_t capacity() const {
		return _str.capacity();
	}

	///
	/// \returns \emph{true} if the string contains no characters, \emph{false} otherwise.
	constexpr bool is_empty() const {
		return size() == 0;
	}

	/// @}


// Access ==============================================================================================================
public:

	/// \name Access
	/// @{

	///
	/// \brief Array Access Operator
	/// \param i the index to access
	/// \returns a reference to the character
	constexpr wchar_t& operator[](size_t i) {
		return _str[i];
	}

	///
	/// \brief Const-Array Access Operator
	/// \param i the index to access
	/// \returns a copy of the character
	constexpr const wchar_t& operator[](size_t i) const {
		return _str[i];
	}

	///
	/// \returns The underlying pointer to the held string
	constexpr wchar_t* data() {
		return _str;
	}

	///
	/// \returns The underlying pointer to the held string
	constexpr const wchar_t* data() const {
		return _str;
	}

	///
	/// \returns The underlying pointer to the held string
	constexpr const wchar_t* cstr() const {
		return _str;
	}

	/// @}


// Examination =========================================================================================================
public:

	/// \name Examination
	/// @{

	///
	/// \returns The length of the string to the first null-terminator
	constexpr size_t length() const {
		return find('\0');
	}

	///
	/// \param str the string to compare against
	/// \param i An offset to start with in \emph{this}
	/// \param n The number of characters to compare
	/// \returns Zero if both strings are equal, otherwise a negative value if lhs appears before rhs according to the
	///          current locale, otherwise a positive value.
	constexpr int compare(const wcstring& str, size_t i = 0, size_t n = npos) const {
		if (i >= size()) { // bounds check
			return -1;
		}
		n = min(min(n, size() - i), str.size());

		return ::wcsncmp(_str + i, str, n);
	}

	///
	/// \brief String Comparison
	/// \param str the string to compare against
	/// \param i An offset to start at in \emph{this}
	/// \param n The number of characters to compare
	/// \returns Zero if both strings are equal, otherwise a negative value if lhs appears before rhs according to the
	///          current locale, otherwise a positive value.
	constexpr int compare(const _wstring& str, size_t i = 0, size_t n = npos) const {
		if (i >= size()) { // bounds check
			return -1;
		}
		n = min(min(n, size() - i), str.size());

		return ::wcsncmp(_str + i, str.data(), n);
	}

	///
	/// \param str The string to compare against
	/// \returns Equivalent to `compare(str) == 0`
	constexpr bool operator==(const wcstring& str) const {
		return compare(str) == 0;
	}

	///
	/// \brief String Equality
	/// \param str The string to compare against
	/// \returns Equivalent to `compare(str) == 0`
	constexpr bool operator==(const _wstring& str) const {
		return compare(str) == 0;
	}

	///
	/// \brief Check if the string contains a character
	/// \param c The character to find
	/// \param i An offset to start at in \emph{this}
	/// \returns \emph{true} if \emph{c} is contained in \emph{this}
	constexpr bool contains(wchar_t c, size_t i = 0) const {
		return find(c, i) != size();
	}

	///
	/// \brief Finds the index of the first occurrence of \emph{c} in the string
	/// \param c the character to find
	/// \param i An offset to start at in \emph{this}
	/// \returns The index of \emph{c} if it occurs in the string, otherwise returns `size()`
	constexpr size_t find(wchar_t c, size_t i = 0) const {
		if (i >= size()) { // bounds check
			return size();
		}

		const wchar_t* loc = ::wcschr(_str + i, c); // get location using strchr
		return loc ? loc - _str : size(); // return size if not found
	}

	///
	/// \brief Finds the index of the first occurrence of \emph{str} in the string.
	/// \param str the string to find
	/// \param i An offset to start at in \emph{this}
	/// \returns The index of \emph{str} if it occurs in the string, otherwise returns `size()`
	constexpr size_t find(const _wstring& str, size_t i = 0) const { // bounds check
		if (i >= size()) { // bounds check
			return size();
		}

		const wchar_t* loc = ::wcsstr(_str, str._str);
		return loc ? loc - _str : size();
	}

	///
	/// \brief Finds the index of the first occurrence of \emph{str} in the string.
	/// \param str the string to find
	/// \param i An offset to start at in \emph{this}
	/// \returns The index of \emph{str} if it occurs in the string, otherwise returns `size()`
	constexpr size_t find(const wcstring& str, size_t i = 0) const {
		if (i + str.size() > size()) { // bounds check
			return size();
		}

		const wchar_t* loc = ::wcsstr(_str + i, str); // get location using strstr
		return loc ? loc - _str : size(); // return size if not found
	}

	///
	/// \brief Finds the index of the last occurrence of \emph{c} in the string.
	/// \param c the string to find
	/// \param i An offset to start at in \emph{this}
	/// \returns The index of \emph{c} if it occurs in the string, otherwise returns `size()`
	constexpr size_t rfind(wchar_t c, size_t i = npos) const {
		if (size() == 0) {
			return size();
		}
		i = min(i, size() - 1); // clamp i to bounds
		do {
			if (_str[i] == c) { // loop backwards looking for c
				return i;
			}
		} while (i--);
		return size(); // base case
	}

	///
	/// \brief Finds the index of the last occurrence of \emph{str} in the string.
	/// \param str the string to find
	/// \param i An offset to start at in \emph{this}
	/// \returns The index of \emph{str} if it occurs in the string, otherwise returns `size()`
	constexpr size_t rfind(const wcstring& str, size_t i = npos) const {
		if (size() == 0) {
			return size();
		}
		const wchar_t first = str[0];
		i = min(i, size() - str.size());
		do {
			if(_str[i] == first) {
				if (compare(str, i) == 0) {
					return i;
				}
			}
		} while (i--);
		return size(); // base case
	}

	///
	/// \brief Finds the index of the last occurrence of \emph{str} in the string.
	/// \param str the string to find
	/// \param i An offset to start at in \emph{this}
	/// \returns The index of \emph{str} if it occurs in the string, otherwise returns `size()`
	constexpr size_t rfind(const _wstring& str, size_t i = npos) const {
		if (size() == 0) {
			return size();
		}
		const wchar_t first = str[0];
		i = min(i, size() - str.size());
		do {
			if(_str[i] == first) {
				if (compare(str, i) == 0) { // loop backwards looking for str
					return i;
				}
			}
		} while (i--);
		return size(); // base case
	}

	///
	/// \brief Retrieve a substring of a string
	/// \param i An offset to start at in \emph{this}
	/// \param n the number of characters
	/// \returns A new string containing the range of characters specified by \emph{i} and \emph{n}
	constexpr _wstring substring(size_t i, size_t n = npos) const {
		if (i >= size() || n == 0) {
			return _wstring("");
		}
		n = fennec::min(n, size() - i);
		_wstring res;
		res._str.allocate(n + 1);
		fennec::memcpy(res.data(), _str + i, n);
		return res;
	}

	/// @}


// Modifiers ===========================================================================================================
public:

	/// \name Modifiers
	/// @{

	///
	/// \brief String Resize
	/// \brief Resizes the underlying allocation to hold \emph{n} characters and a null terminator.
	/// \param n The new size of the string
	constexpr void resize(size_t n) {
		_str.reallocate(n + 1);
		_str[size()] = '\0';
	}

	///
	/// \brief Character Append
	/// \param c A character to append
	/// \returns A new string containing the previous contents and an additional character \emph{c}.
	constexpr _wstring operator+(wchar_t c) const {
		if (_str == nullptr) {
			return _wstring(1, c);
		}
		_wstring res;
		res._str.allocate(capacity() + 1);
		fennec::memcpy(res.data(), _str, size());
		res[size()] = c;
		return res;
	}

	///
	/// \brief Character Prepend
	/// \param c A character to append
	/// \returns A new string containing the character \emph{c} followed by the previous contents.
	friend constexpr _wstring operator+(wchar_t c, const _wstring& str) {
		_wstring res(str.size() + 1);
		res[0] = c;
		fennec::memcpy(res.data() + 1, str.data(), str.size());
		return res;
	}

	///
	/// \param cstr The string to append
	/// \returns A new string containing the previous contents followed by the contents of \emph{cstr}
	constexpr _wstring operator+(const wcstring& cstr) const {
		if (_str == nullptr) {
			return _wstring(cstr);
		}
		_wstring res;
		res._str.allocate(size() + cstr.size() + 1);
		fennec::memcpy(res.data(), _str, size());
		fennec::memcpy(res.data() + size(), cstr, cstr.size());
		return res;
	}

	///
	/// \brief String Append
	/// \param str The string to append
	/// \returns A new string containing the previous contents followed by the contents of \emph{cstr}
	constexpr _wstring operator+(const _wstring& str) const {
		if (_str == nullptr) {
			return _wstring(str);
		}
		if (str.data() == nullptr) {
			return _wstring(*this);
		}
		_wstring res;
		res._str.allocate(size() + str.size() + 1);
		fennec::memcpy(res.data(), _str, size());
		fennec::memcpy(res.data() + size(), str.data(), str.size());
		return res;
	}

	///
	/// \brief Character Append Assignment
	/// \param c A character to append
	/// \returns \emph{this} string containing an additional character \emph{c}.
	constexpr _wstring& operator+=(wchar_t c) {
		if (_str == nullptr) {
			_str.allocate(2);
			_str[0] = c;
			return *this;
		}
		_str.reallocate(capacity() + 1);
		_str[size() - 1] = c;
		return *this;
	}

	///
	/// \param cstr The string to append
	/// \returns \emph{this} string expanded to additionally contain \emph{cstr}
	constexpr _wstring& operator+=(const wcstring& cstr) {
		if (_str == nullptr) {
			return *this = cstr;
		}
		size_t middle = size();
		_str.reallocate(middle + cstr.size() + 1);
		fennec::memcpy(_str + middle, cstr, cstr.size());
		return *this;
	}

	///
	/// \brief String Append Assignment
	/// \param str The string to append
	/// \returns \emph{this} string expanded to additionally contain \emph{str}
	constexpr _wstring& operator+=(const _wstring& str) {
		if (_str == nullptr) {
			return *this = str;
		}
		if (str.data() == nullptr) {
			return *this;
		}
		size_t middle = size();
		_str.reallocate(middle + str.size() + 1);
		fennec::memcpy(_str + middle, str.data(), str.size());
		return *this;
	}

	/// @}


// Iteration ===========================================================================================================
public:

	/// \name Iteration
	/// @{

	///
	/// \returns A pointer to the first character in the string.
	constexpr wchar_t* begin() {
		return _str.data();
	}

	///
	/// \brief Iterable begin()
	/// \returns A pointer to the first character in the string.
	constexpr const wchar_t* begin() const {
		return _str.data();
	}

	///
	/// \returns A pointer to the null terminator of the string.
	constexpr wchar_t* end() {
		return _str.data() + _str.capacity();
	}


	///
	/// \brief Iterable end()
	/// \returns A pointer to the null terminator of the string.
	constexpr const wchar_t* end() const {
		return _str.data() + _str.capacity();
	}

	/// @}


// Private Member Variables ============================================================================================
private:
	alloc_t _str;
};

/// \brief Hashing for `fennec::wstring`
template<typename AllocT>
struct hash<_wstring<AllocT>> : hash<byte_array> {
	constexpr size_t operator()(const _wstring<AllocT>& str) const {
		return hash<byte_array>::operator()(byte_array(str.data(), str.size()));
	}
};

}


#endif // FENNEC_STRING_WSTRING_H
