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

#include "PlatformGLFW.hpp"
#include "WindowGLFW.hpp"
#include "Base/PlatformEnums.hpp"
#include "Base/Logger.hpp"
#include "Host/PlatformProducer.hpp"
#include <GLFW/glfw3.h>

namespace OpenVulkano::GLFW
{
	namespace
	{
		void ErrorCallback(const int error, const char* description)
		{
			Logger::WINDOW->error("GLFW error (e{0}): {1}", error, description);
		}
	}

	PlatformGLFW::~PlatformGLFW()
	{
		if (IsInitialized())
		{
			Close();
		}
	}

	void PlatformGLFW::Init()
	{
		if (!glfwInit()) throw PlatformInitFailedException("Failed to initialize glfw");
		glfwSetErrorCallback(ErrorCallback);
		inputProvider.Init();
		initialized = true;
	}

	void PlatformGLFW::Tick()
	{
		inputProvider.PreTick();
		glfwPollEvents();
		inputProvider.Tick();
	}

	void PlatformGLFW::Close()
	{
		inputProvider.Close();
		glfwTerminate();
		windows.clear();
	}

	IWindow* PlatformGLFW::MakeWindow()
	{
		auto window = std::make_unique<WindowGLFW>(inputProvider);
		IWindow* windowPtr = window.get();
		windows.emplace_back(std::move(window));
		return windowPtr;
	}

	PlatformProducerRegistration<PlatformGLFW> platformRegistration(RenderAPI::Vulkan);
}