package tracker;

import java.util.Scanner;
import tracker.TrackerManagementTCP;
import tracker.TrackerManagementUDP;
import tools.Directories;
import tools.Logger;
import tools.LogLevel;
import tools.TestPort;

/** Tracker implementation
 * First argument of main method is port listened by the tracker, and is mandatory.
 * @author	Louis Royer
 * @author	Flavien Haas
 * @author	JS Auge
 * @version	1.0
 */
public class Tracker {
	private int port;
	private Directories directories;
	private Logger logger;

	/** Constructor with portStr containing a port number.
	 * @param portStr	String containing port number of listening.
	 */
	public Tracker(String portStr) {
		port = Integer.valueOf(Integer.parseInt(portStr));
		directories = new Directories("P2P_JAVA_PROJECT_TRACKER_" + port);
		logger = new Logger(directories.getDataHomeDirectory() + "tracker.log");
		System.out.println("Tracker will listen on port " + port + " and write logs into " + directories.getDataHomeDirectory());
		Scanner scanner = new Scanner(System.in);
		directories.askOpenDataHomeDirectory(null, scanner);
		scanner.close();
	}

	/** Main program entry point
	 * first parameter is port number and is mandatory
	 * to test, run with: java -ea serverP2P.ServerP2P
	 * @param args	parameters
	 */
		public static void main(String [] args) {
			final String defaultPort = "6969";
			final String defaultHostname = "localhost";
			Scanner scanner = new Scanner(System.in);
			Tracker t;

			System.out.println("Tracker Server, enter hostname to bind (default = localhost): ");
			String hostname = scanner.nextLine();
			if(hostname.equals("")){
				hostname = defaultHostname;
				System.out.println("using default hostname : " + hostname);
			}	else{
				System.out.println("using hostname : " + hostname);
			}
			System.out.println("enter port (default = 6969): ");
			String port = scanner.nextLine();
			if(port.equals("")){
				port = defaultPort;
				System.out.println("using default port : " + port);
			} else {
				System.out.println("using port : " + port);
			}
			TestPort testPortTracker = new TestPort();
			if(testPortTracker.testPortTracker(Integer.parseInt(port))){
				t = new Tracker(port);
			}
			else {
				System.out.println("Wrong port (6000 -> 6999), using default port 6969");
				t = new Tracker(defaultPort);
				t.logger.write("Wrong port (6000 -> 6999), using default port 6969", LogLevel.Warning);
			}

			TrackerManagementUDP tmudp = new TrackerManagementUDP(hostname, t.port, t.logger);
			TrackerManagementTCP tmtcp = new TrackerManagementTCP(hostname, t.port, t.logger);
			Thread tudp = new Thread(tmudp);
			tudp.setName("Tracker UDP P2P-JAVA-PROJECT");
			tudp.start();
			Thread ttcp = new Thread(tmtcp);
			ttcp.setName("Tracker TCP P2P-JAVA-PROJECT");
			ttcp.start();
		}
}
