#include <client/MainMenu.h>

#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/multiplayer_api.hpp>
#include <godot_cpp/classes/resource_loader.hpp>
#include <godot_cpp/classes/scene_tree.hpp>

using namespace godot;

namespace blitz {

void MainMenu::_bind_methods() {
	godot::ClassDB::bind_method(godot::D_METHOD("on_connected"), &MainMenu::OnConnected);
	ADD_SIGNAL(MethodInfo("change_scene_to_game", PropertyInfo(Variant::BOOL, "server")));
}

MainMenu::MainMenu() {}

MainMenu::~MainMenu() {}

void MainMenu::_ready() {
	Node* container = find_child("Container");
	DEV_ASSERT(container);

	m_JoinButton = Object::cast_to<Button>(container->find_child("JoinButton"));
	m_CreateButton = Object::cast_to<Button>(container->find_child("CreateButton"));
	m_QuitButton = Object::cast_to<Button>(container->find_child("QuitButton"));

	DEV_ASSERT(m_JoinButton);
	DEV_ASSERT(m_CreateButton);
	DEV_ASSERT(m_QuitButton);

	m_JoinButton->connect("pressed", callable_mp(this, &MainMenu::OnJoinPressed));
	m_CreateButton->connect("pressed", callable_mp(this, &MainMenu::OnCreatePressed));
	m_QuitButton->connect("pressed", callable_mp(this, &MainMenu::OnQuitPressed));


	if (!Engine::get_singleton()->is_editor_hint()) {
		m_NetworkInterface = Object::cast_to<NetworkInterface>(get_parent()->find_child("Network"));
		DEV_ASSERT(m_NetworkInterface);

		m_NetworkInterface->connect("local_player_connected", callable_mp(this, &MainMenu::OnConnected));
		m_NetworkInterface->connect("server_disconnected", callable_mp(this, &MainMenu::OnDisconnected));
	}
}

void MainMenu::OnConnected() {
	emit_signal("change_scene_to_game", get_multiplayer()->is_server());
	set_visible(false);
}

void MainMenu::OnDisconnected() {
	set_visible(true);
	EnableButtons();
}

void MainMenu::OnJoinPressed() {
	DisableButtons();
	m_NetworkInterface->JoinGame("localhost", 25565);
}

void MainMenu::OnCreatePressed() {
	DisableButtons();
	m_NetworkInterface->CreateGame(25565);
}

void MainMenu::OnQuitPressed() {
	get_tree()->quit();
}

void MainMenu::DisableButtons() {
	m_JoinButton->set_disabled(true);
	m_CreateButton->set_disabled(true);
}

void MainMenu::EnableButtons() {
	m_JoinButton->set_disabled(false);
	m_CreateButton->set_disabled(false);
}

}  // namespace blitz