/*
 * 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 "IRecordable.hpp"
#include "Scene/UniformBuffer.hpp"
#include "Vulkan/Resources/UniformBuffer.hpp"

namespace OpenVulkano::Vulkan
{
	class VulkanUniformBuffer : public IRecordable, public ICloseable
	{
	public:
		Scene::UniformBuffer* uBuffer = nullptr;
		UniformBuffer* buffer = nullptr;

		~VulkanUniformBuffer() override
		{
			if (uBuffer) VulkanUniformBuffer::Close();
		}

		virtual void Init(Scene::UniformBuffer* uBuffer, UniformBuffer* uniformBuffer)
		{
			this->uBuffer = uBuffer;
			this->buffer = uniformBuffer;
			uBuffer->renderBuffer = this;
		}

		void Record(VulkanDrawContext* context) override
		{
			buffer->Record(context);
		}

		void Close() override
		{
			if (uBuffer) uBuffer->renderBuffer = nullptr;
			delete buffer;
			uBuffer = nullptr;
			buffer = nullptr;
		}
	};

	struct VulkanUniformBufferDynamic : VulkanUniformBuffer
	{
		uint32_t lastUpdate = 0;

		void Init(Scene::UniformBuffer* buffer, UniformBuffer* uniformBuffer) override
		{
			VulkanUniformBuffer::Init(buffer, uniformBuffer);
			lastUpdate = -1;
		}

		void Record(VulkanDrawContext* context) override
		{
			if(uBuffer->updated) //TODO fix
			{
				uBuffer->updated = false;
				buffer->Update(uBuffer->data, uBuffer->size, context->currentImageId);
			}
			buffer->Record(context);
		}
	};
}
