package eu.nets.sis.eident.demoapp;

import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;

import javax.net.ServerSocketFactory;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.EventListener;

/**
 * Entry class, starts the SpringBoot application
 *
 */
@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
@PropertySource("classpath:application.properties")
public class MainApplication {
	private static final Logger logger = Logger.getLogger(MainApplication.class);
	private static final int PORT = 8080;

	@Value("${base.url}")
	private String baseUrl;
	
	@Value("#{systemProperties['user.dir']}#{systemProperties['file.separator']}${logging.file}") 
	private String loggingPath;
	

	/**
	 * Write logs into console and file, after server started successfully
	 */
	@EventListener(ApplicationReadyEvent.class)
	public void doSomethingAfterStartup() {
		logger.info("E-Ident demo app started");
		System.out.println("\n\nLog file path: "+ loggingPath);
		System.out.println("\n\nPlease point your preferred browser to " + baseUrl + "/eident");
	}

	/**
	 * Entry point to access E-Ident demo application.
	 * Port number can be changed in applications.properties.
	 * 
	 * @param args Command line arguments
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException {
		if(args.length < 2) {
			System.out.println("\n\nERROR: Please provide a valid merchant identifier and a secret code as command line arguments to execute the demo app. "
											+ "If you don't have, please contact Nets support at support.esecurity@nets.eu.\n");
		} else {
			if(isPortAvailable()) {
				SpringApplication.run(MainApplication.class, args);
			}
		}
	}
	
	private static boolean isPortAvailable() throws IOException {
		try (ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(
				MainApplication.PORT, 1, InetAddress.getByName("localhost"))){			
			return true;
		}
		catch (BindException ex) {
			System.out.println("\n\nThe demo application cannot be started. Port 8080 is already in use.\nMake sure no other applications is configured to use this port and try again.");
		}
		return false;
	}
}
