package game;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sudoku.structure.MultiDoku;

public class Game {

	public static enum GameState {
		GameNotStarted, GameGoing
	}

	private final Map<Integer, Player> players;
	private final List<Player> leaderboard;
	private GameState gameState;
	private MultiDoku doku;
	private Instant startTime = null;
	private long gameDuration;

	public Game() {
		this.players = new HashMap<>();
		this.leaderboard = new ArrayList<>();
		this.gameState = GameState.GameNotStarted;
	}

	public Player getPlayerById(int id) {
		return players.get(id);
	}

	public void addPlayer(Player player) {
		players.put(player.getId(), player);
		leaderboard.add(player);
	}

	public void setPlayerRemainingCells(Player player, int newScore) {
		player.setRemainingCells(newScore);
		Collections.sort(this.leaderboard,
				(player1, player2) -> Integer.compare(player1.getRemainingCells(), player2.getRemainingCells()));
	}

	public void removePlayer(int id) {
		this.leaderboard.remove(getPlayerById(id));
		this.players.remove(id);
	}

	public Map<Integer, Player> getPlayers() {
		return players;
	}

	public void startGame(MultiDoku doku, Instant startTime, long gameDuration) {
		this.doku = doku;
		this.gameState = GameState.GameGoing;
		this.startTime = startTime;
		this.gameDuration = gameDuration;
	}

	public void stopGame() {
		this.gameState = GameState.GameNotStarted;
	}

	public GameState getGameState() {
		return gameState;
	}

	public MultiDoku getDoku() {
		return doku;
	}

	public List<Player> getLeaderboard() {
		return leaderboard;
	}

	public Instant getStartTime() {
		return startTime;
	}

	public long getGameDuration() {
		return gameDuration;
	}

}
