#include "MPFW_UI.h"
#define NO_FONT_AWESOME
#include <rlImGui.h>
#include <imgui.h>
#include <iostream>
#include <raylib.h>
#include "MPFW_Console.h"

#include <pugixml.hpp>

bool testActive = true;
MPFW::UI::UIRenderer::UIRenderer()
{
	rlImGuiSetup(true);
}

void MPFW::UI::UIRenderer::Render()
{
	if(rendererIsActive){
		rlImGuiBegin();

		// wH = windowHandle
		for (int wH = 0; wH < windows.size(); wH++) {
			ImGui::Begin(windows[wH].windowTitle.c_str(), &windows[wH].active, windows[wH].menuBar.size() > 0 ? ImGuiWindowFlags_MenuBar : 0);

			if(windows[wH].menuBar.size() != 0){
				
				if(ImGui::BeginMenuBar()){
					
					// mH = menu handle
					for (int mH = 0; mH < windows[wH].menuBar.size(); mH++) {
						if(ImGui::BeginMenu(windows[wH].menuBar[mH].text.c_str())){
							for (int mIH = 0; mIH < windows[wH].menuBar[mH].children.size(); mIH++){
								if (ImGui::MenuItem(windows[wH].menuBar[mH].children[mIH].text.c_str())) {
									cmh->Run(std::format("mode {}", windows[wH].menuBar[mH].children[mIH].commandMode), false);
									cmh->Run(windows[wH].menuBar[mH].children[mIH].command, false);
								}
							}
							ImGui::EndMenu();
						}
					}
					ImGui::EndMenuBar();
				}
			}

			ImGui::End();
		}
		
		rlImGuiEnd();
	}

}


MPFW::UI::UIRenderer::~UIRenderer()
{
}

void MPFW::UI::Window::LoadWindow(std::string path)
{
	pugi::xml_document doc;
	pugi::xml_parse_result result = doc.load_file(path.c_str());

	if (result) {
		pugi::xml_node root = doc.child("window");

		windowTitle = root.child("title").child_value();


		pugi::xml_node menubarRoot = root.child("menubar");
		if (menubarRoot) {
			for (auto const& menu : menubarRoot.children("menu")) {
				Menu m;
				m.text = menu.child("title").child_value();
				for (auto const& menuItem : menu.children("item")) {
					Menu mI;
					mI.text = menuItem.child("title").child_value();
					mI.command = menuItem.child("command").child_value();
					if (menuItem.child("command").attribute("mode")) {
						mI.commandMode = menuItem.child("command").attribute("mode").as_int();
					}
					m.children.push_back(mI);
				}

				menuBar.push_back(m);
			}
		}


	}
	else {
		throw std::runtime_error("couldn't load " + path);
	}

}
