package fr.insa.clavardator.server;

import fr.insa.clavardator.lib.util.Log;

import java.util.List;
import java.util.Scanner;

public class Main {
	private static final int PROXY_PORT = 35750;
	private static final int PRESENCE_PORT = 35650;

	private static final List<String> HELP_ARGS = List.of("-h", "--help");
	private static final List<String> VERSION_ARGS = List.of("-v", "--version");
	private static final List<String> PROXY_ARGS = List.of("-x", "--proxy");
	private static final List<String> PRESENCE_ARGS = List.of("-p", "--presence");

	private static int proxyPort = PROXY_PORT;
	private static int presencePort = PRESENCE_PORT;

	private static void printHelp() {
		System.out.println("\nClavardator INSA presence server v1.0.0\n");
		System.out.println("usage: <command> [options]\n");
		System.out.println("Options:");
		System.out.println("  -h, --help                    Display help message.");
		System.out.println("  -v, --version                 Display version information.");
		System.out.println("  -X <port>, --proxy <port>     Set the proxy port.");
		System.out.println("  -p <port>, --presence <port>  Set the presence server port.");
	}

	private static void printVersion() {
		System.out.println("\nClavardator INSA presence server v1.0.0\n");
	}

	private static int getPort(String value, int defaultValue) {
		int port;
		try {
			port = Integer.parseInt(value.trim());
			if (port <= 1024 || port >= 64000) {
				System.out.println("Port should be between 1024 and 64000. Falling back to default.");
				port = defaultValue;
			}
		} catch (NumberFormatException e) {
			System.out.println("Could not read port " + value + ". Falling back to default.");
			port = defaultValue;
		}
		return port;
	}

	private static void readArgs(String[] args) {
		if (args.length > 0) {
			if (HELP_ARGS.contains(args[0])) {
				printHelp();
				System.exit(0);
			}
			if (VERSION_ARGS.contains(args[0])) {
				printVersion();
				System.exit(0);
			}
			for (int i = 0; i < args.length - 1; i++) {
				if (PROXY_ARGS.contains(args[i])) {
					proxyPort = getPort(args[i + 1], PROXY_PORT);
				}
				if (PRESENCE_ARGS.contains(args[i])) {
					presencePort = getPort(args[i + 1], PRESENCE_PORT);
				}
			}
			if (presencePort == proxyPort) {
				System.out.println("Proxy and presence ports must be different");
				System.exit(1);
			}
		}
	}

	public static void main(String[] args) {

		readArgs(args);

		System.out.println("\nType q then press enter to exit\n");
		Log.v(Main.class.getSimpleName(), "Starting proxy on port " + proxyPort);
		Proxy proxy = new Proxy(proxyPort);
		Log.v(Main.class.getSimpleName(), "Starting presence server on port " + presencePort);
		Presence presence = new Presence(presencePort);

		String line;
		Scanner scanner = new Scanner(System.in);
		do {
			line = scanner.nextLine();
		} while (!line.equals("q"));

		proxy.stop();
		presence.stop();
	}
}
