package gui.menu;

import game.Player;
import gui.widget.SudokuSelector;
import imgui.ImGui;
import imgui.type.ImInt;
import network.client.Client;
import network.server.Server;
import sudoku.structure.MultiDoku;

public class MultiPlayerView extends BaseView {

	private final Client client;
	private final Server server;

	private final SudokuSelector selector;

	private ImInt gameDurationMinutes = new ImInt(10);

	private MultiDoku doku = null;

	public MultiPlayerView(StateMachine stateMachine, Client client, Server server) {
		super(stateMachine);
		this.client = client;
		this.server = server;
		this.selector = new SudokuSelector(false, "Sélectionner le sudoku");
		this.selector.onSelect.connect(this::onSelected);
		this.client.onDisconnect.connect(this::onDisconnect);
		this.client.onGameStarted
				.connect(() -> this.stateMachine.pushState(new MultiPlayerDokuView(stateMachine, client, server)));
	}

	@Override
	public void closeMenu() {
		this.client.forceDisconnect();
		super.closeMenu();
	}

	public void onDisconnect() {
		this.stateMachine.popState();
	}

	private void onSelected(MultiDoku doku) {
		this.doku = doku;
	}

	public void renderGameStatus() {
		if (this.server == null) {
			ImGui.text("En attente de l'administrateur du serveur ...");
		} else {
			renderTimer();
			ImGui.beginDisabled(this.doku == null);
			if (ImGui.button("Démarrer")) {
				this.server.startGame(this.doku, this.gameDurationMinutes.get() * 60);
			}
			ImGui.endDisabled();
			selector.render();
		}
	}

	private void renderPlayers() {
		ImGui.text("Joueurs :");
		{
			for (Player player : this.client.getGame().getPlayers().values()) {
				ImGui.bulletText(player.getPseudo());
			}
		}
	}

	private void renderTimer() {
		if (ImGui.inputInt("Temps de la partie (minutes)", gameDurationMinutes))
			gameDurationMinutes.set(Math.clamp(gameDurationMinutes.get(), 1, 90));
	}

	@Override
	public void render() {
		renderPlayers();
		renderGameStatus();
	}

}
