#include "client/render/gui/MainMenu.h"
#include "client/render/gui/ServerGui.h"

#include "client/Client.h"

#include "server/Server.h"

namespace td {
namespace gui {

MainMenu::MainMenu(client::Client* client) : GuiWidget(client), m_ConnectPort(25565) {
	m_ConnectAddress = "localhost";
	m_ConnectAddress.reserve(256);
}

MainMenu::~MainMenu() {
	if (m_Server != nullptr)
		m_Server->Stop();
}

void MainMenu::Render() {
	if (m_Server != nullptr && !m_Server->IsRunning()) {
		m_Server.reset(); // destroying server if it stoped
		m_ServerGui.reset();
	}

	if(m_Server != nullptr){
		m_ServerGui->Render();
	}

	if (m_Client->IsConnected()) return;

	ImGui::Begin("Main Menu");
	if (ImGui::Button("Rejoindre une partie##join")) {
		ImGui::OpenPopup("Rejoindre une partie##join_popup");
	}
	if (ImGui::Button("Créer une partie")) {
		ImGui::OpenPopup("Créer une partie##create_popup");
	}
	if (ImGui::Button("Options")) {
		// TODO: add settings
	}

	if (ImGui::BeginPopup("Rejoindre une partie##join_popup")) {
		ImGui::InputText("Server Adress", &m_ConnectAddress.front(), m_ConnectAddress.capacity());
		ImGui::InputInt("Port", &m_ConnectPort, -1);
		if (ImGui::Button("Rejoindre")) {
			GetClient()->Connect(td::network::Dns::Resolve(m_ConnectAddress), m_ConnectPort);
			m_TriedToConnect = true;
		}
		if (m_TriedToConnect) {
			ImGui::Text("Impossible de se connecter");
		}
		ImGui::EndPopup();
	} else {
		m_TriedToConnect = false;
	}

	if (ImGui::BeginPopup("Créer une partie##create_popup")) {
		ImGui::InputInt("Server Port", &m_ServerPort, -1);
		ImGui::Text("%s", std::string("Fichier de monde sélectionné : " + (m_WorldFilePath.empty() ? std::string("Aucun") : m_WorldFilePath)).c_str());
		ImGui::SameLine();
		if (ImGui::Button("Ouvrir un fichier")) {
			ImGui::OpenPopup("WorldFileDialog");
		}
		if (m_FileDialog.showFileDialog("WorldFileDialog", imgui_addons::ImGuiFileBrowser::DialogMode::OPEN, ImVec2(600, 300), ".tdmap")) {
			m_WorldFilePath = m_FileDialog.selected_path;
		}
		if (m_Server != nullptr) ImGui::BeginDisabled();
		if (ImGui::Button("Créer")) {
			if (!StartServer()) {
				m_TriedToCreate = true;
			} else {
				GetClient()->Connect(td::network::Dns::Resolve("localhost"), m_ServerPort);
			}
		}
		else if (m_Server != nullptr) ImGui::EndDisabled();
		if (m_TriedToCreate)
			ImGui::Text("Failed to launch server");
		ImGui::EndPopup();
	} else {
		m_TriedToConnect = false;
	}

	ImGui::End();
}

bool MainMenu::StartServer() {
	if (m_WorldFilePath.empty())
		return false;
	m_Server = std::make_unique<td::server::Server>();
	m_Server->LoadMap(m_WorldFilePath);
	if (!m_Server->Start(m_ServerPort, false)) {
		m_Server.reset();
		return false;
	}
	m_ServerGui = std::make_unique<ServerGui>(m_Client, m_Server.get());
	return true;
}

} // namespace gui
} // namespace td
