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

#include "array.hpp"
#include "concepts.hpp"
#include "bit.hpp"
#include "error.hpp"
#include "initializerlist.hpp"
#include "iterator.hpp"
#include "math.hpp"
#include "memory.hpp"
#include "new.hpp"
#include "types.hpp"
#include "utility.hpp"

namespace ox {

template<typename PlatSpec>
struct VectorMemMap {
	typename PlatSpec::size_t size = 0;
	typename PlatSpec::size_t cap = 0;
	typename PlatSpec::PtrType items = 0;
	uint8_t allocator = 0;
};

template<typename PlatSpec>
[[nodiscard]]
constexpr auto sizeOf(const VectorMemMap<PlatSpec> &t) noexcept {
	constexpr auto padding = [](std::size_t size, std::size_t al) {
		return size - size % al;
	};
	std::size_t size = 0;
	size += sizeof(t.size);
	size += padding(size, PlatSpec::alignOf(t.cap));
	size += sizeof(t.cap);
	size += padding(size, PlatSpec::alignOf(t.items));
	size += sizeof(t.items);
	size += padding(size, PlatSpec::alignOf(t.allocator));
	size += sizeof(t.allocator);
	return size;
}

template<typename PlatSpec>
[[nodiscard]]
constexpr auto alignOf(const VectorMemMap<PlatSpec>&) noexcept {
	const typename PlatSpec::size_t i = 0;
	return PlatSpec::alignOf(i);
}

namespace detail {

template<typename T, typename Allocator, std::size_t Size = 1>
struct VectorAllocator {
	private:
		ox::Array<AllocAlias<T>, Size> m_data = {};
		Allocator m_allocator;
	public:
		constexpr VectorAllocator() noexcept = default;
		constexpr VectorAllocator(const VectorAllocator&) noexcept = default;
		constexpr VectorAllocator(VectorAllocator&&) noexcept = default;

		constexpr void allocate(T **items, std::size_t cap) noexcept {
			// small vector optimization cannot be done it constexpr, but it doesn't really matter in constexpr
			if (std::is_constant_evaluated() || cap > Size) {
				*items = m_allocator.allocate(cap);
			} else {
				*items = reinterpret_cast<T*>(m_data.data());
			}
		}

		constexpr void moveConstructItemsFrom(T **items, VectorAllocator &src, const std::size_t count, const std::size_t cap) noexcept {
			// this totally idiotic redundant check (&& count <= Size) is required to address a bug in devkitARM,
			// try removing it later
			if (cap <= Size && count <= Size) {
				const auto dstItems = reinterpret_cast<T*>(m_data.data());
				const auto srcItems = reinterpret_cast<T*>(src.m_data.data());
				for (auto i = 0u; i < count; ++i) {
					std::construct_at<T>(&dstItems[i], std::move(srcItems[i]));
				}
				*items = reinterpret_cast<T*>(m_data.data());
			}
		}

		constexpr void moveItemsFrom(T **items, VectorAllocator &src, const std::size_t count, const std::size_t cap) noexcept {
			// this totally idiotic redundant check (&& count <= Size) is required to address a bug in devkitARM,
			// try removing it later
			if (cap <= Size && count <= Size) {
				const auto dstItems = reinterpret_cast<T*>(m_data.data());
				const auto srcItems = reinterpret_cast<T*>(src.m_data.data());
				for (std::size_t i = 0; i < count; ++i) {
					dstItems[i] = std::move(srcItems[i]);
				}
				*items = reinterpret_cast<T*>(m_data.data());
			}
		}

		constexpr void deallocate(T *items, std::size_t cap) noexcept {
			// small vector optimization cannot be done it constexpr, but it doesn't really matter in constexpr
			if (std::is_constant_evaluated() || (items && static_cast<void*>(items) != static_cast<void*>(m_data.data()))) {
				m_allocator.deallocate(items, cap);
			}
		}

};

template<typename T, typename Allocator>
struct VectorAllocator<T, Allocator, 0> {
	private:
		Allocator m_allocator;
	public:
		constexpr VectorAllocator() noexcept = default;
		constexpr VectorAllocator(const VectorAllocator&) noexcept = default;
		constexpr VectorAllocator(VectorAllocator&&) noexcept = default;

		constexpr void allocate(T **items, std::size_t cap) noexcept {
			*items = m_allocator.allocate(cap);
		}

		[[maybe_unused]]
		constexpr void moveConstructItemsFrom(T**, VectorAllocator&, const std::size_t, const std::size_t) noexcept {
		}

		[[maybe_unused]]
		constexpr void moveItemsFrom(T**, VectorAllocator&, const std::size_t, const std::size_t) noexcept {
		}

		constexpr void deallocate(T *items, std::size_t cap) noexcept {
			if (items) {
				m_allocator.deallocate(items, cap);
			}
		}

};

}

template<typename T, std::size_t SmallVectorSize = 0, typename Allocator = std::allocator<T>>
class Vector {

	public:
		using value_type = T;
		using size_type = std::size_t;

		template<typename RefType = T&, typename PtrType = T*, bool reverse = false>
		struct iterator: public Iterator<std::bidirectional_iterator_tag, T> {
			private:
				PtrType m_t = nullptr;
				size_type m_offset = 0;
				size_type m_max = 0;

			public:
				constexpr iterator() noexcept = default;

				constexpr iterator(PtrType t, size_type offset, size_type max) noexcept {
					m_t = t;
					m_offset = offset;
					m_max = max;
				}

				constexpr auto offset() const noexcept {
					return m_offset;
				}

				constexpr iterator operator+(size_type s) const noexcept {
					if constexpr(reverse) {
						return iterator(m_t, max<size_type>(m_offset - s, 0), m_max);
					} else {
						return iterator(m_t, min<size_type>(m_offset + s, m_max), m_max);
					}
				}

				constexpr auto operator-(const iterator &other) const noexcept {
					if constexpr(reverse) {
						return m_offset + other.m_offset;
					} else {
						return m_offset - other.m_offset;
					}
				}

				constexpr iterator operator-(size_type s) const noexcept {
					if constexpr(reverse) {
						return iterator(m_t, min<size_type>(m_offset + s, m_max), m_max);
					} else {
						return iterator(m_t, max<size_type>(m_offset - s, 0), m_max);
					}
				}

				constexpr iterator &operator+=(size_type s) noexcept {
					if constexpr(reverse) {
						m_offset = max<size_type>(m_offset - s, 0);
					} else {
						m_offset = min(m_offset + s, m_max);
					}
					return *this;
				}

				constexpr iterator &operator-=(size_type s) noexcept {
					if constexpr(reverse) {
						m_offset = min(m_offset + s, m_max);
					} else {
						m_offset = max<size_type>(m_offset - s, 0);
					}
					return *this;
				}

				constexpr iterator &operator++() noexcept {
					return operator+=(1);
				}

				constexpr iterator &operator--() noexcept {
					return operator-=(1);
				}

				constexpr RefType operator*() const noexcept {
					return m_t[m_offset];
				}

				constexpr RefType operator[](size_type s) const noexcept {
					return m_t[s];
				}

				constexpr bool operator<(const iterator &other) const noexcept {
					return m_offset < other.m_offset;
				}

				constexpr bool operator>(const iterator &other) const noexcept {
					return m_offset > other.m_offset;
				}

				constexpr bool operator<=(const iterator &other) const noexcept {
					return m_offset <= other.m_offset;
				}

				constexpr bool operator>=(const iterator &other) const noexcept {
					return m_offset >= other.m_offset;
				}

				constexpr bool operator==(const iterator &other) const noexcept {
					return m_t == other.m_t && m_offset == other.m_offset && m_max == other.m_max;
				}

				constexpr bool operator!=(const iterator &other) const noexcept {
					return m_t != other.m_t || m_offset != other.m_offset || m_max != other.m_max;
				}

		};

	private:
		static constexpr auto initialSize = SmallVectorSize > 0 ? SmallVectorSize : 50;
		std::size_t m_size = 0;
		std::size_t m_cap = 0;
		T *m_items = nullptr;
		detail::VectorAllocator<T, Allocator, SmallVectorSize> m_allocator;

	public:
		constexpr Vector() noexcept = default;

		explicit constexpr Vector(std::size_t size) noexcept;

		constexpr Vector(std::initializer_list<T> list) noexcept;

		constexpr Vector(const Vector &other);

		constexpr Vector(Vector &&other) noexcept;

		constexpr ~Vector();

		constexpr iterator<> begin() noexcept {
			return iterator<>(m_items, 0, m_size);
		}

		constexpr iterator<> end() noexcept {
			return iterator<>(m_items, m_size, m_size);
		}

		[[nodiscard]]
		constexpr iterator<const T&, const T*> begin() const noexcept {
			return iterator<const T&, const T*>(m_items, 0, m_size);
		}

		[[nodiscard]]
		constexpr iterator<const T&, const T*> end() const noexcept {
			return iterator<const T&, const T*>(m_items, m_size, m_size);
		}

		[[nodiscard]]
		constexpr iterator<const T&, const T*> cbegin() const noexcept {
			return iterator<const T&, const T*>(m_items, 0, m_size);
		}

		[[nodiscard]]
		constexpr iterator<const T&, const T*> cend() const noexcept {
			return iterator<const T&, const T*>(m_items, m_size, m_size);
		}

		[[nodiscard]]
		constexpr iterator<T&, T*, true> rbegin() noexcept {
			return iterator<T&, T*, true>(m_items, m_size - 1, m_size);
		}

		[[nodiscard]]
		constexpr iterator<T&, T*, true> rend() noexcept {
			return iterator<T&, T*, true>(m_items, MaxValue<size_type>, m_size);
		}

		[[nodiscard]]
		constexpr iterator<const T&, const T*, true> crbegin() const noexcept {
			return iterator<const T&, const T*, true>(m_items, m_size - 1, m_size);
		}

		[[nodiscard]]
		constexpr iterator<const T&, const T*, true> crend() const noexcept {
			return iterator<const T&, const T*, true>(m_items, MaxValue<size_type>, m_size);
		}

		[[nodiscard]]
		constexpr iterator<const T&, const T*, true> rbegin() const noexcept {
			return iterator<const T&, const T*, true>(m_items, m_size - 1, m_size);
		}

		[[nodiscard]]
		constexpr iterator<const T&, const T*, true> rend() const noexcept {
			return iterator<const T&, const T*, true>(m_items, MaxValue<size_type>, m_size);
		}

		constexpr bool operator==(const Vector &other) const;

		constexpr Vector &operator=(const Vector &other);

		constexpr Vector &operator=(Vector &&other) noexcept;

		constexpr T &operator[](std::size_t i) noexcept;

		constexpr const T &operator[](std::size_t i) const noexcept;

		[[nodiscard]]
		Result<T&> front() noexcept;

		[[nodiscard]]
		Result<const T&> front() const noexcept;

		[[nodiscard]]
		constexpr Result<T&> back() noexcept;

		[[nodiscard]]
		constexpr Result<const T&> back() const noexcept;

		[[nodiscard]]
		constexpr std::size_t size() const noexcept;

		[[nodiscard]]
		constexpr bool empty() const noexcept;

		constexpr void clear();

		constexpr void resize(std::size_t size);

		[[nodiscard]]
		constexpr T *data() noexcept {
			return m_items;
		}

		[[nodiscard]]
		constexpr const T *data() const noexcept {
			return m_items;
		}

		[[nodiscard]]
		constexpr bool contains(const T&) const;

		constexpr void insert(std::size_t pos, std::size_t cnt, const T &val);

		constexpr void insert(std::size_t pos, const T &val);

		template<typename... Args>
		constexpr T &emplace_back(Args&&... args);

		constexpr void push_back(const T &item);

		constexpr void pop_back();

		/**
		 * Removes an item from the Vector.
		 * @param pos iterator at the point to remove
		 * @return Error if index is out of bounds
		 */
		constexpr Result<iterator<>> erase(const iterator<> &pos);

		/**
		 * Removes an item from the Vector.
		 * @param pos position of item to remove
		 * @return Error if index is out of bounds
		 */
		constexpr Result<iterator<>> erase(std::size_t pos);

		/**
		 * Moves the last item in the Vector to position pos and decrements the
		 * size by 1.
		 * @param pos position of item to remove
		 * @return Error if index is out of bounds
		 */
		constexpr Error unordered_erase(std::size_t pos);

	private:
		constexpr void expandCap(std::size_t cap);

};

template<typename T, std::size_t SmallVectorSize, typename Allocator, typename RefType, bool reverse>
using VectorIt = typename Vector<T, SmallVectorSize, Allocator>::template iterator<RefType, reverse>;

template<typename T, std::size_t SmallVectorSize, typename Allocator, typename RefType, bool reverse>
constexpr VectorIt<T, SmallVectorSize, Allocator, RefType, reverse> operator+(std::size_t n, const VectorIt<T, SmallVectorSize, Allocator, RefType, reverse> &a) {
	return a + n;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Vector<T, SmallVectorSize, Allocator>::Vector(std::size_t size) noexcept {
	m_size = size;
	m_cap = m_size;
	m_allocator.allocate(&m_items, m_cap);
	for (std::size_t i = 0; i < size; ++i) {
		std::construct_at(&m_items[i]);
	}
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Vector<T, SmallVectorSize, Allocator>::Vector(std::initializer_list<T> list) noexcept {
	for (auto &item : list) {
		emplace_back(item);
	}
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Vector<T, SmallVectorSize, Allocator>::Vector(const Vector &other) {
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_allocator.allocate(&m_items, other.m_cap);
	for (std::size_t i = 0; i < m_size; ++i) {
		std::construct_at(&m_items[i], other.m_items[i]);
	}
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Vector<T, SmallVectorSize, Allocator>::Vector(Vector &&other) noexcept {
	m_size = other.m_size;
	m_cap = other.m_cap;
	m_items = other.m_items;
	m_allocator.moveConstructItemsFrom(&m_items, other.m_allocator, m_size, m_cap);
	other.m_size = 0;
	other.m_cap = 0;
	other.m_items = nullptr;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Vector<T, SmallVectorSize, Allocator>::~Vector() {
	clear();
	m_allocator.deallocate(m_items, m_cap);
	m_items = nullptr;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr bool Vector<T, SmallVectorSize, Allocator>::operator==(const Vector &other) const {
	if (m_size != other.m_size) {
		return false;
	}
	for (std::size_t i = 0; i < m_size; i++) {
		if (!(m_items[i] == other.m_items[i])) {
			return false;
		}
	}
	return true;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Vector<T, SmallVectorSize, Allocator> &Vector<T, SmallVectorSize, Allocator>::operator=(const Vector &other) {
	if (this != &other) {
		clear();
		m_allocator.deallocate(m_items, m_cap);
		m_items = nullptr;
		m_size = other.m_size;
		m_cap = other.m_cap;
		m_allocator.allocate(&m_items, other.m_cap);
		for (std::size_t i = 0; i < m_size; i++) {
			std::construct_at(&m_items[i], other.m_items[i]);
		}
	}
	return *this;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Vector<T, SmallVectorSize, Allocator> &Vector<T, SmallVectorSize, Allocator>::operator=(Vector &&other) noexcept {
	if (this != &other) {
		clear();
		m_allocator.deallocate(m_items, m_cap);
		m_size = other.m_size;
		m_cap = other.m_cap;
		m_items = other.m_items;
		m_allocator.moveItemsFrom(&m_items, other.m_allocator, m_size, m_cap);
		other.m_size = 0;
		other.m_cap = 0;
		other.m_items = nullptr;
	}
	return *this;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr T &Vector<T, SmallVectorSize, Allocator>::operator[](std::size_t i) noexcept {
	return m_items[i];
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr const T &Vector<T, SmallVectorSize, Allocator>::operator[](std::size_t i) const noexcept {
	return m_items[i];
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
Result<T&> Vector<T, SmallVectorSize, Allocator>::front() noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*reinterpret_cast<T*>(&v), OxError(1)};
	}
	return m_items[0];
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
Result<const T&> Vector<T, SmallVectorSize, Allocator>::front() const noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*reinterpret_cast<T*>(&v), OxError(1)};
	}
	return m_items[0];
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Result<T&> Vector<T, SmallVectorSize, Allocator>::back() noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*reinterpret_cast<T*>(&v), OxError(1)};
	}
	return m_items[m_size - 1];
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Result<const T&> Vector<T, SmallVectorSize, Allocator>::back() const noexcept {
	if (!m_size) {
		AllocAlias<T> v;
		return {*reinterpret_cast<T*>(&v), OxError(1)};
	}
	return m_items[m_size - 1];
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr std::size_t Vector<T, SmallVectorSize, Allocator>::size() const noexcept {
	return m_size;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr bool Vector<T, SmallVectorSize, Allocator>::empty() const noexcept {
	return !m_size;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr void Vector<T, SmallVectorSize, Allocator>::clear() {
	if constexpr(is_class<T>()) {
		for (std::size_t i = 0; i < m_size; ++i) {
			m_items[i].~T();
		}
	}
	m_size = 0;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr void Vector<T, SmallVectorSize, Allocator>::resize(std::size_t size) {
	if (m_cap < size) {
		expandCap(size);
	}
	if (m_size < size) {
		for (std::size_t i = m_size; i < size; i++) {
			std::construct_at(&m_items[i]);
		}
	} else {
		for (std::size_t i = size; i < m_size; i++) {
			m_items[i].~T();
		}
	}
	m_size = size;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr bool Vector<T, SmallVectorSize, Allocator>::contains(const T &v) const {
	for (std::size_t i = 0; i < m_size; i++) {
		if (m_items[i] == v) {
			return true;
		}
	}
	return false;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr void Vector<T, SmallVectorSize, Allocator>::insert(std::size_t pos, std::size_t cnt, const T &val) {
	// TODO: insert should ideally have its own expandCap
	if (m_size + cnt > m_cap) {
		expandCap(m_cap ? m_size + cnt : initialSize);
	}
	if (pos < m_size) {
		for (auto i = m_size + cnt - 1; i > pos; --i) {
			std::construct_at(&m_items[i], std::move(m_items[i - cnt]));
		}
		m_items[pos] = val;
	} else {
		for (auto i = 0u; i < cnt; ++i) {
			std::construct_at(&m_items[pos + i], val);
		}
	}
	++m_size;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr void Vector<T, SmallVectorSize, Allocator>::insert(std::size_t pos, const T &val) {
	// TODO: insert should ideally have its own expandCap
	if (m_size == m_cap) {
		expandCap(m_cap ? m_cap * 2 : initialSize);
	}
	if (pos < m_size) {
		for (auto i = m_size; i > pos; --i) {
			std::construct_at(&m_items[i], std::move(m_items[i - 1]));
		}
		m_items[pos] = val;
	} else {
		std::construct_at(&m_items[pos], val);
	}
	++m_size;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
template<typename... Args>
constexpr T &Vector<T, SmallVectorSize, Allocator>::emplace_back(Args&&... args) {
	if (m_size == m_cap) {
		expandCap(m_cap ? m_cap * 2 : initialSize);
	}
	auto out = std::construct_at(&m_items[m_size], ox::forward<Args>(args)...);
	++m_size;
	return *out;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr void Vector<T, SmallVectorSize, Allocator>::push_back(const T &item) {
	if (m_size == m_cap) {
		expandCap(m_cap ? m_cap * 2 : initialSize);
	}
	std::construct_at(&m_items[m_size], item);
	++m_size;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr void Vector<T, SmallVectorSize, Allocator>::pop_back() {
	--m_size;
	m_items[m_size].~T();
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Result<typename Vector<T, SmallVectorSize, Allocator>::template iterator<T&, T*, false>> Vector<T, SmallVectorSize, Allocator>::erase(const iterator<> &pos) {
	return erase(pos.offset());
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Result<typename Vector<T, SmallVectorSize, Allocator>::template iterator<T&, T*, false>> Vector<T, SmallVectorSize, Allocator>::erase(std::size_t pos) {
	if (pos >= m_size) {
		return OxError(1, "Vector::erase failed: pos is greater than Vector size");
	}
	--m_size;
	for (auto i = pos; i < m_size; ++i) {
		m_items[i] = std::move(m_items[i + 1]);
	}
	m_items[m_size].~T();
	return begin() + pos;
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr Error Vector<T, SmallVectorSize, Allocator>::unordered_erase(std::size_t pos) {
	if (pos >= m_size) {
		return OxError(1);
	}
	--m_size;
	m_items[pos] = std::move(m_items[m_size]);
	m_items[m_size].~T();
	return OxError(0);
}

template<typename T, std::size_t SmallVectorSize, typename Allocator>
constexpr void Vector<T, SmallVectorSize, Allocator>::expandCap(std::size_t cap) {
	const auto oldItems = m_items;
	const auto oldCap = m_cap;
	m_cap = cap;
	m_allocator.allocate(&m_items, cap);
	if (oldItems) { // move over old items
		const auto itRange = ox::min(cap, m_size);
		for (std::size_t i = 0; i < itRange; ++i) {
			std::construct_at(&m_items[i], std::move(oldItems[i]));
			oldItems[i].~T();
		}
		m_allocator.deallocate(oldItems, oldCap);
	}
}


template<typename PlatSpec, typename T>
[[nodiscard]]
constexpr auto alignOf(const Vector<T>&) noexcept {
	const typename PlatSpec::size_t i = 0;
	return PlatSpec::alignOf(i);
}

}
