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

// Makre usre the Molten include is first!
#include <MoltenVK/mvk_vulkan.h>

#include "MetalViewWindow.h"
#include "Base/Logger.hpp"
#include "Host/GraphicsAppManager.hpp"

#import <MetalKit/MTKView.h>

namespace OpenVulkano
{
	vk::SurfaceKHR MetalViewWindow::CreateSurface(const vk::Instance& instance, const vk::AllocationCallbacks* pAllocator)
	{
		VkMetalSurfaceCreateInfoEXT surfaceCreateInfo;
		surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
		surfaceCreateInfo.pNext = NULL;
		surfaceCreateInfo.flags = 0;
		surfaceCreateInfo.pLayer = (CAMetalLayer*) caMetalLayer;

		VkSurfaceKHR surface;
		auto err = vkCreateMetalSurfaceEXT(static_cast<VkInstance>(instance), &surfaceCreateInfo, NULL, &surface);
		return {surface};
	}

	std::vector<std::string> MetalViewWindow::GetRequiredInstanceExtensions()
	{
		return {}; //TODO
	}

	void MetalViewWindow::OnResize(uint32_t newWidth, uint32_t newHeight)
	{
		Logger::WINDOW->debug("Window (id: {0}) resized (width: {1}, height: {2})", GetWindowId(), newWidth, newHeight);
		if (handler)
			handler->OnWindowResize(this, newWidth, newHeight);
	}

	void MetalViewWindow::TickHandler()
	{
		if (tickHandler)
		{
			if (auto graphApp = dynamic_cast<GraphicsAppManager*>(handler))
			{
				graphApp->LoopTick();
			}
		}
	}
}
