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

///
/// \file fennec/renderers/vulkan/lib/instance.h
/// \brief
///
///
/// \details
/// \author Medusa Slockbower
///
/// \copyright Copyright © 2025 - 2026 Medusa Slockbower ([GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html))
///
///


#ifndef FENNEC_RENDERERS_VULKAN_LIB_INSTANCE_H
#define FENNEC_RENDERERS_VULKAN_LIB_INSTANCE_H

#include <fennec/renderers/vulkan/lib/forward.h>
#include <fennec/renderers/vulkan/lib/app_info.h>
#include <fennec/renderers/vulkan/lib/physical_device.h>

#include <fennec/containers/dynarray.h>

namespace fennec::vk
{

///
/// \brief Wrapper class for VkInstance
struct instance {

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

	/// \name Definitions
	/// @{

	using create_flags = VkInstanceCreateFlags; //!< Alias for VkInstanceCreateFlags


	///
	/// \brief Wrapper class for VkInstanceCreateInfo
	struct create_info : private VkInstanceCreateInfo {

	// Constructors & Destructor ---------------------------------------------------------------------------------------
	public:

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

		///
		/// \brief Null App Info Constructor
		/// \param flags The flags to create the instance with.
		///
		/// \note Acts as Default Constructor.
		create_info(
			create_flags flags = {}, nullptr_t = nullptr
		) : VkInstanceCreateInfo {
			.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
			.pNext = nullptr,
			.flags = flags,
			.pApplicationInfo = nullptr,
			.enabledLayerCount = 0,
			.ppEnabledLayerNames = nullptr,
			.enabledExtensionCount = 0,
			.ppEnabledExtensionNames = nullptr,
		} {
		}

		///
		/// \brief App Info Constructor
		/// \param flags The flags to create the instance with.
		/// \param info A const-qualified reference to an \ref fennec::vk::app_info "app_info" object.
		///
		/// \note The object referenced by \emph{info} must have a lifetime that extends until an
		/// \ref fennec::vk::instance "instance" is constructed.
		create_info(
			create_flags flags, const app_info& info
		) : VkInstanceCreateInfo {
			.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
			.pNext = nullptr,
			.flags = flags,
			.pApplicationInfo = info,
			.enabledLayerCount = 0,
			.ppEnabledLayerNames = nullptr,
			.enabledExtensionCount = 0,
			.ppEnabledExtensionNames = nullptr,
		} {
		}

		///
		/// \brief Layer Constructor
		/// \tparam LayersN The number of layers
		/// \param flags The flags to create the instance with.
		/// \param info A const-qualified reference to an \ref fennec::vk::app_info "app_info" object.
		/// \param layers An array of layer names to enable.
		///
		/// \note The object referenced by \emph{info} must have a lifetime that extends until an
		/// \ref fennec::vk::instance "instance" is constructed.
		template<size_t LayersN>
		create_info(
			create_flags flags, const app_info& info,
			const cstring (&layers)[LayersN], nullptr_t
		) : VkInstanceCreateInfo {
			.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
			.pNext = nullptr,
			.flags = flags,
			.pApplicationInfo = info,
			.enabledLayerCount = LayersN,
			.ppEnabledLayerNames = nullptr,
			.enabledExtensionCount = 0,
			.ppEnabledExtensionNames = nullptr,
		} {
			_layers.reserve(LayersN);
			for (const auto& layer : layers) {
				_layers.push_back(layer);
			}

			ppEnabledLayerNames = _layers.data();
			ppEnabledExtensionNames = _extensions.data();
		}


		///
		/// \brief Extension Constructor
		/// \tparam ExtensionsN The number of extensions
		/// \param flags The flags to create the instance with.
		/// \param info A const-qualified reference to an \ref fennec::vk::app_info "app_info" object.
		/// \param extensions An array of extension names to enable.
		///
		/// \note The object referenced by \emph{info} must have a lifetime that extends until an
		/// \ref fennec::vk::instance "instance" is constructed.
		template<size_t ExtensionsN>
		create_info(
			create_flags flags, const app_info& info,
			nullptr_t, const cstring (&extensions)[ExtensionsN]
		) : VkInstanceCreateInfo {
			.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
			.pNext = nullptr,
			.flags = flags,
			.pApplicationInfo = info,
			.enabledLayerCount = 0,
			.ppEnabledLayerNames = nullptr,
			.enabledExtensionCount = ExtensionsN,
			.ppEnabledExtensionNames = nullptr,
		} {
			_extensions.reserve(ExtensionsN);
			for (const auto& extension : extensions) {
				_extensions.push_back(extension);
			}

			ppEnabledLayerNames = _layers.data();
			ppEnabledExtensionNames = _extensions.data();
		}

		///
		/// \brief Layer-Extension Constructor
		/// \tparam LayersN The number of layers
		/// \tparam ExtensionsN The number of extensions
		/// \param flags The flags to create the instance with.
		/// \param info A const-qualified reference to an \ref fennec::vk::app_info "app_info" object.
		/// \param layers An array of layer names to enable.
		/// \param extensions An array of extension names to enable.
		///
		/// \note The object referenced by \emph{info} must have a lifetime that extends until an
		/// \ref fennec::vk::instance "instance" is constructed.
		template<size_t LayersN, size_t ExtensionsN>
		create_info(
			create_flags flags, const app_info& info,
			const cstring (&layers)[LayersN], const cstring (&extensions)[ExtensionsN]
		) : VkInstanceCreateInfo {
			.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
			.pNext = nullptr,
			.flags = flags,
			.pApplicationInfo = info,
			.enabledLayerCount = LayersN,
			.ppEnabledLayerNames = nullptr,
			.enabledExtensionCount = ExtensionsN,
			.ppEnabledExtensionNames = nullptr,
		} {
			_layers.reserve(LayersN);
			for (const auto& layer : layers) {
				_layers.push_back(layer);
			}

			_extensions.reserve(ExtensionsN);
			for (const auto& extension : extensions) {
				_extensions.push_back(extension);
			}

			ppEnabledLayerNames = _layers.data();
			ppEnabledExtensionNames = _extensions.data();
		}

		///
		/// \brief Dynamic Layer Constructor
		/// \param flags The flags to create the instance with.
		/// \param info A const-qualified reference to an \ref fennec::vk::app_info "app_info" object.
		/// \param layers An array of layer names to enable.
		///
		/// \note The object referenced by \emph{info} must have a lifetime that extends until an
		/// \ref fennec::vk::instance "instance" is constructed.
		create_info(
			create_flags flags, const app_info& info,
			const dynarray<cstring>& layers, nullptr_t
		) : VkInstanceCreateInfo {
			.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
			.pNext = nullptr,
			.flags = flags,
			.pApplicationInfo = info,
			.enabledLayerCount = static_cast<uint32_t>(layers.size()),
			.ppEnabledLayerNames = nullptr,
			.enabledExtensionCount = 0,
			.ppEnabledExtensionNames = nullptr,
		} {
			_layers.reserve(enabledLayerCount);
			for (const auto& layer : layers) {
				_layers.push_back(layer);
			}

			ppEnabledLayerNames = _layers.data();
			ppEnabledExtensionNames = _extensions.data();
		}

		///
		/// \brief Dynamic Extension Constructor
		/// \param flags The flags to create the instance with.
		/// \param info A const-qualified reference to an \ref fennec::vk::app_info "app_info" object.
		/// \param extensions An array of extension names to enable.
		/// \param ext An extension structure.
		///
		/// \note The object referenced by \emph{info} must have a lifetime that extends until an
		/// \ref fennec::vk::instance "instance" is constructed.
		create_info(
			create_flags flags, const app_info& info,
			nullptr_t, const dynarray<cstring>& extensions
		) : VkInstanceCreateInfo {
			.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
			.pNext = nullptr,
			.flags = flags,
			.pApplicationInfo = info,
			.enabledLayerCount = 0,
			.ppEnabledLayerNames = nullptr,
			.enabledExtensionCount = static_cast<uint32_t>(extensions.size()),
			.ppEnabledExtensionNames = nullptr,
		} {
			_extensions.reserve(enabledExtensionCount);
			for (const auto& extension : extensions) {
				_extensions.push_back(extension);
			}

			ppEnabledLayerNames = _layers.data();
			ppEnabledExtensionNames = _extensions.data();
		}

		///
		/// \brief Dynamic Layer-Extension Constructor
		/// \param flags The flags to create the instance with.
		/// \param info A const-qualified reference to an \ref fennec::vk::app_info "app_info" object.
		/// \param layers An array of layer names to enable.
		/// \param extensions An array of extension names to enable.
		///
		/// \note The object referenced by \emph{info} must have a lifetime that extends until an
		/// \ref fennec::vk::instance "instance" is constructed.
		create_info(
			create_flags flags, const app_info& info,
			const dynarray<cstring>& layers, const dynarray<cstring>& extensions
		) : VkInstanceCreateInfo {
			.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
			.pNext = nullptr,
			.flags = flags,
			.pApplicationInfo = info,
			.enabledLayerCount = static_cast<uint32_t>(layers.size()),
			.ppEnabledLayerNames = nullptr,
			.enabledExtensionCount = static_cast<uint32_t>(extensions.size()),
			.ppEnabledExtensionNames = nullptr,
		} {
			_layers.reserve(enabledLayerCount);
			for (const auto& layer : layers) {
				_layers.push_back(layer);
			}

			_extensions.reserve(enabledExtensionCount);
			for (const auto& extension : extensions) {
				_extensions.push_back(extension);
			}

			ppEnabledLayerNames = _layers.data();
			ppEnabledExtensionNames = _extensions.data();
		}

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

		/// @}


	// Assignment ------------------------------------------------------------------------------------------------------
	public:

		/// \name Assignment
		/// @{

		///
		/// \brief Copy Assignment
		/// \param rhs Create info to copy
		/// \returns A reference to \emph{this} after having copied \emph{rhs}
		create_info& operator=(const create_info& rhs) {
			pNext            = rhs.pNext;
			flags            = rhs.flags;
			pApplicationInfo = rhs.pApplicationInfo;

			_layers             = rhs._layers;
			ppEnabledLayerNames = _layers.data();
			enabledLayerCount   = _layers.size();

			_extensions             = rhs._extensions;
			ppEnabledExtensionNames = _extensions.data();
			enabledExtensionCount   = _extensions.size();

			return *this;
		}

		///
		/// \brief Move Assignment
		/// \param rhs Create info to move
		/// \returns A reference to \emph{this} after having taken ownership of \emph{rhs}
		create_info& operator=(create_info&& rhs) noexcept {
			pNext            = rhs.pNext;
			flags            = rhs.flags;
			pApplicationInfo = rhs.pApplicationInfo;

			_layers             = move(rhs._layers);
			ppEnabledLayerNames = _layers.data();
			enabledLayerCount   = _layers.size();

			_extensions             = move(rhs._extensions);
			ppEnabledExtensionNames = _extensions.data();
			enabledExtensionCount   = _extensions.size();

			return *this;
		}

		/// @}


	// Layers & Extensions ---------------------------------------------------------------------------------------------
	public:

		/// \name Layers & Extensions
		/// @{

		///
		/// \brief Enable the specified layer.
		/// \param layer The layer name to enable.
		void enable_layer(const cstring& layer) {
			_layers.emplace_back(layer.data());
			enabledLayerCount = _layers.size();
			ppEnabledLayerNames = _layers.data();
		}

		///
		/// \brief Enable the specified extension.
		/// \param extension The extension name to enable.
		void enable_extension(const cstring& extension) {
			_extensions.emplace_back(extension.data());
			enabledExtensionCount = _extensions.size();
			ppEnabledExtensionNames = _extensions.data();
		}

		///
		/// \brief Attach a debugger.
		/// \param dbg The debugger to attach.
		void attach_debugger(const debugger& dbg) {
			_info = make_unique<debugger::info>(dbg);
			pNext = *_info;
		}

		/// @}


	// Implicit Conversions --------------------------------------------------------------------------------------------
	public:

		/// \name Implicit Conversions
		/// @{

		///
		/// \returns \emph{this} as if it were a pointer to the underlying type, \emph{VkInstanceCreateInfo}.
		operator VkInstanceCreateInfo*() noexcept {
			return this;
		}

		///
		/// \brief Implicit Pointer Conversion
		/// \returns \emph{this} as if it were a pointer to the underlying type, \emph{VkInstanceCreateInfo}.
		operator const VkInstanceCreateInfo*() const noexcept {
			return this;
		}

		/// @}


	// Private Member Variables ----------------------------------------------------------------------------------------
	private:
		dynarray<const char*> _layers;
		dynarray<const char*> _extensions;
		unique_ptr<debugger::info> _info;
	};

	/// @}


private:
	using device_list = dynarray<physical_device>;



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

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

	///
	/// \brief Instance Constructor
	/// \param info The info to create the instance with.
	/// \details Initializes a new \emph{VkInstance} using \emph{info}.
	instance(const create_info& info) {
		assertf((vkCreateInstance(info, nullptr, &_handle)), "Failed to create Vulkan instance.");

		uint32_t count = 0;
		vkEnumeratePhysicalDevices(_handle, &count, nullptr);
		dynarray<VkPhysicalDevice> devices(count);
		vkEnumeratePhysicalDevices(_handle, &count, devices.data());

		_devices = devices;
	}

	///
	/// Copy Constructor
	/// \details Deleted, no semantics for copying an instance
	instance(const instance&) = delete;

	///
	/// \brief Instance Destructor
	/// \details Cleans up the held \emph{VkInstance}.
	~instance() {
		vkDestroyInstance(_handle, nullptr);
	}

	/// @}



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

	const device_list& available_devices() const {
		return _devices;
	}


// Access ==============================================================================================================

	operator VkInstance() const {
		return _handle;
	}

// Private Member Variables ============================================================================================
private:
	VkInstance  _handle;
	device_list _devices;
};

}

#endif // FENNEC_RENDERERS_VULKAN_LIB_INSTANCE_H