package gui.menu;

import game.Player;
import gui.widget.LeaderboardRenderer;
import gui.widget.MultiPlayerCompleteProgress;
import gui.widget.SudokuRenderer;
import gui.widget.TimerRenderer;
import imgui.ImGui;
import network.client.Client;
import network.server.Server;
import sudoku.solver.BacktrackingSolver;
import sudoku.solver.Solver;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;

public class MultiPlayerDokuView extends BaseView {

	private final Client client;
	private final Server server;
	private final SudokuRenderer sudokuRenderer;
	private final LeaderboardRenderer leaderboardRenderer;
	private final TimerRenderer timerRenderer;
	private final MultiPlayerCompleteProgress completeProgress;

	public MultiPlayerDokuView(StateMachine stateMachine, Client client, Server server) {
		super(stateMachine);
		this.client = client;
		this.server = server;
		this.sudokuRenderer = new SudokuRenderer(this.client.getGame().getDoku());
		this.leaderboardRenderer = new LeaderboardRenderer(client.getGame(), client.getPlayer());
		this.sudokuRenderer.onCellChange.connect(this::onCellChange);
		this.client.onDisconnect.connect(this::onDisconnect);
		this.client.onGameEnd.connect(this::onGameEnd);
		this.timerRenderer = new TimerRenderer(this.client.getGame().getStartTime(), this.client.getGame().getGameDuration());
		this.completeProgress = new MultiPlayerCompleteProgress(this.client.getGame());
	}

	private void onGameEnd(Player winner) {
		MultiDoku doku = this.client.getGame().getDoku();
		doku.clearMutableCells();
		Solver solver = new BacktrackingSolver();
		solver.solve(doku);
		this.stateMachine.overrideState(new EndGameView(stateMachine, doku, winner));
	}

	private void onCellChange(Cell cell) {
		this.client.sendCellChange(cell);
	}

	public void onDisconnect() {
		if (server == null) {
			closeMenu();
		}
	}

	@Override
	public void render() {
		this.timerRenderer.render();
		this.leaderboardRenderer.render();
		this.completeProgress.render();
		this.sudokuRenderer.render();
		if (ImGui.button("Quitter")) {
			this.client.stop();
			this.closeMenu(3);
		}
	}

}
