/*
 * 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 "ImGuiImplOpenVulkano.hpp"
#include "Base/FrameMetadata.hpp"
#include <imgui.h>

namespace OpenVulkano
{
	ImGuiImplOpenVulkano ImGuiImplOpenVulkano::INSTANCE{};

	void ImGuiImplOpenVulkano::Init(OpenVulkano::IWindow* window)
	{
		ImGuiIO& io = ImGui::GetIO();
		IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");

		m_window = window;

		io.BackendPlatformUserData = this;
		io.BackendPlatformName = "imgui_impl_ios";

		/*io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
		io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
		io.ClipboardUserData = bd->Window;*/


		ImGuiViewport* mainViewport = ImGui::GetMainViewport();
		mainViewport->PlatformHandle = m_window;
	}

	void ImGuiImplOpenVulkano::NewFrame()
	{
		ImGuiIO& io = ImGui::GetIO();
		IM_ASSERT(m_window != nullptr && "Did you call Init?");

		// Setup display size (every frame to accommodate for window resizing)
		/*int w, h;
		int display_w, display_h;
		glfwGetWindowSize(bd->Window, &w, &h);
		glfwGetFramebufferSize(bd->Window, &display_w, &display_h);
		io.DisplaySize = ImVec2((float)w, (float)h);
		if (w > 0 && h > 0)
			io.DisplayFramebufferScale = ImVec2((float)display_w / (float)w, (float)display_h / (float)h);*/
		io.DisplaySize = { static_cast<float>(m_window->GetWidth()), static_cast<float>(m_window->GetHeight()) };
		io.DisplayFramebufferScale = { m_window->GetContentScale(), m_window->GetContentScale() };

		//if (bd->WantUpdateMonitors)
			//ImGui_ImplGlfw_UpdateMonitors();

		// Setup time step
		io.DeltaTime = CURRENT_FRAME.frameTime;

		//TODO handle inputs
	}

	void ImGuiImplOpenVulkano::Close()
	{
		ImGuiIO& io = ImGui::GetIO();

#ifndef __APPLE__
		ImGui::DestroyPlatformWindows();
#endif
		
		io.BackendPlatformName = nullptr;
		io.BackendPlatformUserData = nullptr;
		io.BackendFlags = ImGuiBackendFlags_None;
	}
}
