#include "client/gui/OptionsMenu.h"

#include "client/Client.h"
#include "client/display/InputManager.h"
#include "client/gui/FPSMenu.h"
#include <SDL2/SDL.h>
#include <imgui.h>

namespace blitz {
namespace gui {

OptionsMenu::OptionsMenu(GuiWidget* parent, Client* client) : GuiWidget(parent, client) {
	AddWidget(std::make_unique<FPSMenu>(this, client));
	InputManager::BindKeyDownCallback(std::bind(&OptionsMenu::OnKeyEvent, this, std::placeholders::_1));

	m_ShowFPS = m_Client->GetConfig()->IsFPSDisplayEnabled();
	m_SubWidgets[0]->SetState(m_ShowFPS);

	m_VSync = m_Client->GetConfig()->IsVSyncEnabled();
	SDL_GL_SetSwapInterval(m_VSync);
}

void OptionsMenu::OnKeyEvent(int key) {}

void OptionsMenu::Render() {
	GuiWidget::Render();

	if (ImGui::IsKeyPressed(ImGuiKey_Escape) && m_Client->IsConnected() && !IsEnabled()) {
		Enable();
		ImGui::GetIO().ClearInputKeys();  // releases the Escape key
		InputManager::GrabMouse(false);
	}

	if (!IsEnabled())
		return;

	const static int paddingHeight = 40;
	const static int startPos = 15;

	SetNextWindowFullScreen();

	ImGui::Begin("OptionsWindow", nullptr, GetWindowFullScreenFlags());
	{
		ImGui::SetCursorPosX(startPos);

		ImGui::Text("Options");

		ImGui::NewLine();

		if (ImGui::Checkbox("AFFICHER LES FPS", &m_ShowFPS)) {
			m_SubWidgets[0]->SetState(m_ShowFPS);
			m_Client->GetConfig()->SetFPSDisplay(m_ShowFPS);
		}

		if (ImGui::Checkbox("VSync", &m_VSync)) {
			SDL_GL_SetSwapInterval(m_VSync);
			m_Client->GetConfig()->SetVSync(m_VSync);
		}

		if (ImGui::Button("Retour") || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
			Disable();
			if (m_Client->IsConnected()) {
				InputManager::GrabMouse(true);
			} else {
				m_Parent->Enable();
			}
		}

		if (m_Client->IsConnected()) {
			if (ImGui::Button("Quitter la partie")) {
				m_Client->Disconnect();
				Disable();
				m_Parent->Enable();
			}
		}
	}
	ImGui::End();
}

}  // namespace gui
}  // namespace blitz
