package serverP2P;
import serverP2P.ServerManagementUDP;
import serverP2P.ServerManagementTCP;
import tools.Directories;
import tools.Logger;

/** Server only implementation
 * First argument of main method is port listened by the server, and is mandatory.
 * @author	Louis Royer
 * @author	Flavien Haas
 * @author	JS Auge
 * @version	1.0
 */
public class ServerP2P {
	private int port;
	private Directories directories;
	static private final String subdir = "seeded/";
	private Logger logger;

	/** Constructor with portStr containing a port number.
	 * @param portStr	String containing port number of listening.
	 */
	public ServerP2P(String portStr) {
		port = Integer.valueOf(Integer.parseInt(portStr));
		directories = new Directories("P2P_JAVA_PROJECT_SERVER_" + port);
		directories.createSubdir(subdir);
		logger = new Logger(directories.getDataHomeDirectory() + "server.log");
		System.out.println("Server will listen on port " + port + " and serve files from " + directories.getDataHomeDirectory() + subdir);
		directories.askOpenDataHomeDirectory(subdir);
	}

	/** Main program entry point
	 * first parameter is port number and is mandatory
	 * to test, run with: java -ea serverP2P.ServerP2P -- <portNumber>
	 * @param args	parameters
	 */
		public static void main(String [] args) {

			if (args[1].equals("help") || args[1].equals("-h") || args[1].equals("h")){
				System.out.println("usage : java -ea serveurP2P.ServeurP2P -- <serveurPORT> <trackerHOSTNAME> <trackerPORT>");
			}
			else{
				ServerP2P s = new ServerP2P(args[1]);
				ServerManagementUDP smudp = new ServerManagementUDP(s.directories.getDataHomeDirectory() + subdir, s.port, s.logger);
				ServerManagementTCP smtcp = new ServerManagementTCP(s.directories.getDataHomeDirectory() + subdir, s.port, s.logger);
				Thread tudp = new Thread(smudp);
				tudp.setName("server UDP P2P-JAVA-PROJECT");
				tudp.start();
				Thread ttcp = new Thread(smtcp);
				ttcp.setName("server TCP P2P-JAVA-PROJECT");
				ttcp.start();
			}
	}

}
