package network.client;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Random;

import common.ConsumerSignal;
import common.Signal;
import game.Game;
import game.Player;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.LoginPacket;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;

public class Client {
	private final ClientConnexion clientConnection;
	private final Game game;

	public final Signal onConnect = new Signal();
	public final Signal onDisconnect = new Signal();
	public final Signal onClosed = new Signal();
	public final Signal onGameStarted = new Signal();
	public final ConsumerSignal<Player> onGameEnd = new ConsumerSignal<>();

	Player player;

	String disconnectReason = null;

	public Client(String address, short port) throws UnknownHostException, IOException {
		this.clientConnection = new ClientConnexion(address, port, this);
		this.game = new Game();
		// temp
		Random r = new Random();
		login("Player" + r.nextInt());
	}

	public void login(String pseudo) {
		System.out.println("Logging in with pseudo " + pseudo + " ...");
		this.clientConnection.sendPacket(new LoginPacket(pseudo));
	}

	public void stop() {
		this.clientConnection.close();
	}

	public void addPlayer(Player player) {
		this.game.addPlayer(player);
	}

	public Game getGame() {
		return game;
	}

	public String getDisconnectReason() {
		return disconnectReason;
	}

	public void forceDisconnect() {
		this.onClosed.emit();
		stop();
	}

	public void sendCellChange(Cell cell) {
		MultiDoku doku = getGame().getDoku();
		for (int sudokuIndex = 0; sudokuIndex < doku.getNbSubGrids(); sudokuIndex++) {
			Sudoku sudoku = doku.getSubGrid(sudokuIndex);
			int cellIndex = sudoku.getCells().indexOf(cell);
			if (cellIndex != -1) {
				this.clientConnection.sendPacket(new ChangeCellPacket(sudokuIndex, cellIndex, cell.getSymbolIndex()));
				return;
			}
		}
	}

	public Player getPlayer() {
		return player;
	}

}
