package gui.widget;

import game.Game;
import game.Player;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.ImVec4;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiStyleVar;

public class LeaderboardRenderer {

	private final Game game;
	private final Player currentPlayer;

	private final float cellHeight = 75;
	private final ImVec2 cellSize = new ImVec2(12 * cellHeight, cellHeight);
	private final ImVec2 rankSize = new ImVec2(cellHeight, cellHeight);
	private final ImVec2 scoreSize = rankSize;
	private final ImVec2 nameSize = new ImVec2(cellSize.x - cellHeight * 2.0f, cellHeight);
	private final ImVec4 cellColorPlayer = new ImVec4(0.20f, 0.67f, 1.0f, 0.5f);
	private final ImVec4 cellColorEnemy = new ImVec4(1.0f, 0.0f, 0.0f, 0.5f);
	private final int maxPlayersShowed = 2;

	private final int emptyCellCount;

	public LeaderboardRenderer(Game game, Player player) {
		this.game = game;
		this.currentPlayer = player;
		this.emptyCellCount = game.getDoku().getEmptyCells().size();
	}

	private void renderRank(int rank) {
		ImGui.button(Integer.toString(rank), rankSize);
	}

	private void renderName(String name) {
		ImGui.button(name, nameSize);
	}

	private void renderScore(int score) {
		ImGui.button(Integer.toString(score), scoreSize);
	}

	private void renderCell(Player player, int rank, ImVec4 color) {
		ImGui.pushStyleColor(ImGuiCol.Button, color);
		ImGui.pushStyleColor(ImGuiCol.ButtonHovered, color);
		ImGui.pushStyleColor(ImGuiCol.ButtonActive, color);
		ImGui.beginChild(player.getPseudo() + "##" + player.getId(), cellSize);
		renderRank(rank);
		ImGui.sameLine();
		renderName(player.getPseudo());
		ImGui.sameLine();
		renderScore(emptyCellCount - player.getRemainingCells());
		ImGui.endChild();
		ImGui.popStyleColor(3);
	}

	public void render() {
		var displaySize = ImGui.getIO().getDisplaySize();
		ImGui.setCursorPosX(displaySize.x / 2.0f - cellSize.x / 2.0f);
		ImGui.beginChild("Leaderboard", new ImVec2(cellSize.x + 15.0f, cellHeight * maxPlayersShowed));
		ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, new ImVec2());
		ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 3.0f);
		for (int i = 0; i < game.getLeaderboard().size(); i++) {
			Player player = game.getLeaderboard().get(i);
			renderCell(player, i + 1, player == currentPlayer ? cellColorPlayer : cellColorEnemy);
		}
		ImGui.popStyleVar(2);
		ImGui.endChild();
	}

}
