package gui.menu;

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

import imgui.ImGui;
import network.client.Client;
import network.server.Server;

public class ConnexionStatusView extends BaseView {

	private Client client;
	private Server server;

	private String displayText = "Connecting ...";

	public ConnexionStatusView(StateMachine stateMachine, String address, short port)
			throws UnknownHostException, IOException {
		super(stateMachine);
		Thread t = new Thread(() -> {
			try {
				this.client = new Client(address, port);
				bindListeners();
			} catch (IOException e) {
				e.printStackTrace();
				onDisconnect();
			}
		});
		t.start();
	}

	public ConnexionStatusView(StateMachine stateMachine, short port) throws UnknownHostException, IOException {
		super(stateMachine);
		Thread t = new Thread(() -> {
			try {
				this.server = new Server(port);
				this.client = new Client("localhost", port);
				bindListeners();
			} catch (IOException e) {
				e.printStackTrace();
				onDisconnect();
			}
		});
		t.start();
	}

	private void bindListeners() {
		this.client.onConnect.connect(this::onConnect);
		this.client.onClosed.connect(this::onLeave);
		this.client.onDisconnect.connect(this::onDisconnect);
	}

	private ConnexionStatusView(StateMachine stateMachine, Server server, Client client) {
		super(stateMachine);
		this.client = client;
		this.server = server;
	}

	public void onConnect() {
		this.stateMachine.pushState(new MultiPlayerView(stateMachine, client, server));
	}

	public void onDisconnect() {
		if (client != null) {
			String reason = client.getDisconnectReason();
			if (reason == null)
				displayText = "Le serveur a fermé la connexion !";
			else
				displayText = "Vous avez été déconnecté ! Raison : " + client.getDisconnectReason();
		} else {
			displayText = "La connexion a échoué !";
		}

	}

	public void onLeave() {
		this.client = null;
		// on passe le menu de la connexion
		this.closeMenu();
	}

	@Override
	public void render() {
		ImGui.text(displayText);
		renderReturnButton();
	}

	@Override
	public void closeMenu() {
		super.closeMenu();
		cleanResources();
	}

	@Override
	public void cleanResources() {
		// System.out.println("Bye bye !");
		if (this.server != null) {
			this.server.stop();
		}
		if (this.client != null) {
			this.client.stop();
		}
	}

}
