// =====================================================================================================================
//  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_FILESYSTEM_PATH_H
#define FENNEC_FILESYSTEM_PATH_H

#include <fennec/filesystem/path.h>
#include <fennec/string/string.h>

namespace fennec
{

///
/// \brief struct for handling file paths
///
/// \details This structure makes no guarantees about the validity of a path.
///          Operations do not examine the system's file structure.
struct path {

// Definitions =========================================================================================================
public:

	class iterator;
	friend class iterator;


// Current Working Director ============================================================================================
public:

	/// \name Current Working Directory
	/// @{

	/// \brief Get the current working directory
	/// \returns a path containing the absolute path to the working directory
	static path get_current();

	/// \brief Set the current working directory
	/// \param path the path to the new working directory
	/// \returns a path containing the absolute path to the working directory
	static path set_current(const path& path);

	/// @}


// Constructors & Destructor ===========================================================================================
public:

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

	///
	/// \brief Default Constructor, returns the root of the current working directory
	path() : _str("/") { }

	///
	/// \brief C-String Conversion Constructor
	/// \param str the cstring to convert
	path(const cstring& str)
		: _str(str) {
		if (str.size() > 2 && str[str.size() - 1] == '/') {
			_str = _str.substring(0, str.size() - 1);
		}
	}

	///
	/// \brief String Conversion Constructor
	/// \param str the string to convert
	path(const string& str)
	: _str(str) {
		if (str.size() > 2 && str[str.size() - 1] == '/') {
			_str = _str.substring(0, str.size() - 1);
		}
	}

	///
	/// \brief Path Copy Constructor
	/// \param p the path to copy
	path(const path& p)
		: _str(p._str) {
	}

	///
	/// \brief Path Move Constructor
	/// \param p the path to take ownership of
	path(path&& p) noexcept : _str(move(p._str)) { }

	///
	/// \brief Destructor
	~path() = default;

	/// @}


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

	/// \name Assignment
	/// @{

	///
	/// \brief C-String Assignment Operator
	/// \param str the cstring to assign
	/// \returns a reference to \emph{this} after assigning \emph{p}
	template<size_t n>
	path& operator=(const char (&str)[n]) {
		_str = str;
		return *this;
	}

	///
	/// \brief C-String Assignment Operator
	/// \param p the cstring to assign
	/// \returns a reference to \emph{this} after assigning \emph{p}
	path& operator=(const cstring& p) {
		_str = p;
		return *this;
	}

	///
	/// \brief String Assignment Operator
	/// \param p the cstring to assign
	/// \returns a reference to \emph{this} after assigning \emph{p}
	path& operator=(const string& p) {
		_str = p;
		return *this;
	}

	///
	/// \brief Path Copy Assignment Operator
	/// \param p the path to copy
	/// \returns a reference to \emph{this} after copying \emph{p}
	path& operator=(const path& p) {
		_str = p._str;
		return *this;
	}

	///
	/// \brief Path Move Assignment Operator
	/// \param p the path to take ownership of
	/// \returns a reference to \emph{this} after taking ownership of \emph{p}
	path& operator=(path&& p) noexcept {
		_str = move(p._str);
		return *this;
	}

	/// @}


// Comparison ==========================================================================================================
public:

	/// \name Comparison
	/// @{

	///
	/// \brief path equality operator
	/// \param p the path to compare against
	/// \returns \emph{true} if the paths are identical, \emph{false} otherwise. relative paths are not resolved
	bool operator==(const path& p) const {
		return _str == p._str;
	}

	/// @}


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

	/// \name Modifiers
	/// @{

	///
	/// \brief path append operator
	/// \param str the filename to append
	/// \returns a path containing the current path followed by \emph{str}
	path operator/(const cstring& str) const {
		return path(_str + '/' + str);
	}

	///
	/// \brief path append operator
	/// \param str the filename to append
	/// \returns a path containing the current path followed by \emph{str}
	path operator/(const string& str) const {
		return path(_str + '/' + str);
	}

	///
	/// \brief path append operator
	/// \param p the path to append
	/// \returns a path containing the current path followed by \emph{p}
	path operator/(const path& p) const {
		return path(_str + '/' + p._str);
	}

	/// @}

	///
	/// \brief the filename of the current path
	/// \returns a string containing a copy of the filename
	string filename() const {
		const size_t i = _str.rfind('/');
		return _str.substring(i + 1);
	}

	///
	/// \returns the underlying string representation
	const string& str() const { return _str; }

	///
	/// \returns the underlying C-Style string representation
	const char* cstr() const { return _str.cstr(); }

	///
	/// \returns \emph{true} if the path is empty or points to root
	bool is_empty() {
		const size_t size = _str.size();
		if (size == 0) return true;
#if FENNEC_PLATFORM_WINDOWS
		return (_str[1] == ':' && size == 3);
#else
		return (_str[0] == '/' && size == 1);
#endif
	}

	///
	/// \returns a copy of the path with the filename removed
	path parent() const {
#ifdef FENNEC_PLATFORM_WINDOWS
		size_t start = _str.size() - 1;
		start = _str[start] == '/' || _str[start] == '\\' ? start - 1 : start;

		size_t r = _str.rfind('/', start);
		size_t l = _str.rfind('\\', start);
		if (r == _str.size()) {
			start = l;
		}
		else if (l == _str.size()) {
			start = r;
		}
		else {
			start = max(r, l);
		}
		return _str.substring(0, start);
#else
		size_t start = _str.size();
		start = _str[start] == '/' ? start - 1 : start;
		return path(_str.substring(0, _str.rfind('/', start)));
#endif
	}

	///
	/// \brief absolute path
	/// \returns a copy of the path with relative paths resolved
	path absolute() const {
		path parse = *this;
		path working; working._str.resize(0);

// Check if this is a rooted path;
#ifdef FENNEC_PLATFORM_WINDOWS
		if (_str[1] != ':') {
#else
		if (_str[0] != '/') {
#endif
			working = get_current();
		}

		while (not parse.is_empty()) {
			// Handle dots
			while (not parse.is_empty() && parse._str[0] == '.') {
				// Check for ".."
				if (parse._str[1] == '.') {
					// ".."
					if (parse._str.size() == 2) {
						parse = path();
						working = working.parent();
					}
					// "../"
					else if (parse._str[2] == '/') {
						working = working.parent();
						parse._str = parse._str.substring(3);
					}
				}
				// "./"
				else if (parse._str[1] == '/') {
					parse._str = parse._str.substring(2);
				}
			}

			if (parse.is_empty()) break;

			// Push the path
			const size_t loc = parse._str.find('/');
			working._str += '/';
			working._str += parse._str.substring(0, loc);
			parse._str = parse._str.substring(loc + 1);
		}

		return working;
	}


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

	/// \name Iteration
	/// @{

	///
	/// \brief C++ Iterator Specification \emph{begin()}
	/// \returns an iterator at the first filename in the path
	iterator begin() const {
		return iterator(this, 0);
	}

	///
	/// \brief C++ Iterator Specification \emph{end()}
	/// \returns an iterator to the end of the path
	iterator end() const {
		return iterator(this, _str.size());
	}

	///
	/// \brief C++ Iterator Specification \emph{iterator}
	class iterator {
	public:
		///
		/// \brief copy constructor
		/// \param it the iterator to copy
		constexpr iterator(const iterator& it) = default;

		///
		/// \brief move constructor
		/// \param it the iterator to move
		constexpr iterator(iterator&& it) noexcept = default;

		///
		/// \brief dereference operator
		/// \returns copy of the current file in the path
		constexpr string operator*() const {
			if ((*_str)[_pos] == '/') {
				return string("");
			}

			size_t e = _str->find('/', _pos);
			return _str->substring(_pos, e - _pos);
		}

		///
		/// \brief prefix increment operator
		/// \returns \emph{self} after having moved to the next element in the list
		constexpr iterator& operator++() {
			_pos = min(_str->find('/', _pos) + 1, _str->size());
			return *this;
		}

		///
		/// \brief postfix increment operator
		/// \returns \emph{self} before having moved to the next element in the list
		constexpr iterator operator++(int) {
			const iterator it = *this;
			this->operator++();
			return it;
		}

		///
		/// \brief iterator equality operator
		/// \param rhs the iterator to compare with
		/// \returns \emph{true} if the iterators are identical, \emph{false} otherwise
		constexpr bool operator==(const iterator& rhs) const {
			return _str == rhs._str and _pos == rhs._pos;
		}

		///
		/// \brief iterator inequality operator
		/// \param rhs the iterator to compare with
		/// \returns \emph{true} if the iterators are different, \emph{false} otherwise
		constexpr bool operator!=(const iterator& rhs) const {
			return _str != rhs._str or _pos != rhs._pos;
		}

	private:
		const string* _str;
		size_t _pos;

		constexpr iterator(const path* path, size_t p)
			: _str(&path->_str)
			, _pos(p) {

			// Handle end()
			if (p == _str->size()) {
				return;
			}

			// Handle rooted paths
#ifdef FENNEC_PLATFORM_WINDOWS
			if ((*_str)[1] == ':') {
				_pos = max(_pos, size_t(3));
			}
#else
			if ((*_str)[0] == '/') {
				_pos = max(_pos, size_t(1));
			}
#endif

			// Ensure we are at the start of a directory/file name
			if (_pos != 0 && (*_str)[_pos - 1] != '/') {
				_pos = _str->find('/', _pos) + 1;
			}
		}

		friend struct path;
	};

	/// @}

private:
	string _str;
};

}

#endif // FENNEC_FILESYSTEM_PATH_H
