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

#pragma once

#include "Base/ICloseable.hpp"
#include "Image.hpp"
#include "Device.hpp"
#include <cstdint>
#include <vulkan/vulkan.hpp>


namespace OpenVulkano::Vulkan
{
	class RenderPass;

	class FrameBuffer : ICloseable
	{
		Image depthBuffer;
		std::vector<vk::Framebuffer> frameBuffers;
		vk::Format depthBufferFormat = vk::Format::eUndefined, colorFormat = vk::Format::eUndefined;
		vk::Extent3D size;
		std::vector<RenderPass*> renderPasses;
		vk::Viewport fullscreenViewport;
		vk::Rect2D fullscreenScissor;
		Device* device = nullptr;
		bool useDepthBuffer;
	protected:
		uint32_t currentFrameBufferId = 0;

		FrameBuffer() = default;

		virtual ~FrameBuffer()
		{
			if (device) FrameBuffer::Close();
		}

		void Init(Device* device, vk::Extent3D size, bool useDepthBuffer = true);

		void SetCurrentFrameId(uint32_t id) { currentFrameBufferId = id; }

		[[nodiscard]] uint32_t GetCurrentFrameId() const { return currentFrameBufferId; }

	public:
		void RegisterRenderPass(RenderPass* renderPass);

	protected:
		void Resize(vk::Extent3D size);

		void Close() override
		{
			DestroyFrameBuffer();
			if(depthBuffer) depthBuffer.Close();
			device = nullptr;
		}

	protected:

		virtual void CreateDepthStencil();

		virtual void CreateFrameBuffer();

		void DestroyFrameBuffer();

		[[nodiscard]] virtual vk::Format FindColorFormat() = 0;

		[[nodiscard]] virtual vk::Format FindDepthFormat()
		{
			return device->GetSupportedDepthFormat();
		}

	public:
		[[nodiscard]] vk::Format GetColorFormat() const { return colorFormat; }

		[[nodiscard]] vk::Format GetDepthFormat() const { return depthBufferFormat; }

		[[nodiscard]] virtual std::vector<IImage*> GetImages() = 0;

		[[nodiscard]] bool UseDepthBuffer() const { return useDepthBuffer; }

		[[nodiscard]] const vk::Extent3D& GetSize3D() const { return size; }

		[[nodiscard]] vk::Extent2D GetSize2D() const { return { size.width, size.height }; }

		[[nodiscard]] vk::Framebuffer& GetCurrentFrameBuffer() { return frameBuffers[currentFrameBufferId]; }

		[[nodiscard]] const vk::Viewport& GetFullscreenViewport() const { return fullscreenViewport; }

		[[nodiscard]] const vk::Rect2D& GetFullscreenScissor() const { return fullscreenScissor; }

		[[nodiscard]] const Image& GetCurrentDepthBuffer() { return depthBuffer; }
	};
}
