package com.refactorerl.ui.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;

import com.refactorerl.ui.communication.ReferlProxy;
import com.refactorerl.ui.communication.process.ReferlProcess;

public class Common {

	public static Handler[] createLogHandlers() {

		try {

			ConsoleHandler ch = new ConsoleHandler();
			ch.setLevel(Level.ALL);

			Handler[] hs = new Handler[] { ch };
			return hs;

		} catch (SecurityException e) {
			System.err.println("Unable to start logger");
		}
		return null;
	}

	public static String createRandomName() {
		return "tests"
				+ new BigInteger(130, Common.random).toString(32).substring(0,
						7);
	}

	public static Random random = new Random();

	public static Pair<ReferlProcess, ReferlProxy>  startProxy(String baseDirPath) {

		String aliveName = Common.createRandomName();
		String dataDir = System.getProperty("java.io.tmpdir") + File.separator + "com_refactorerl_ui_test_referl_data";
		
		File f = new File(dataDir);
		if(f.exists() && !f.isDirectory()){
			System.out.println("Unable to create data folder (exists, but not a directory)");
			return null;
		} else if(f.exists()) {
			f.delete();
		}
		
		f.mkdir();
		
		ReferlProcess process = new ReferlProcess(baseDirPath, aliveName,
				ReferlProcess.DatabaseType.NIF, dataDir,
				Common.createLogHandlers());

		if (!process.start()) {
			System.out.println("Unable to start process");
			return null;
		}

		MockEventDispatcher eventDispatcher = new MockEventDispatcher();
		eventDispatcher.start();

		String address;
		try {
			address = process.getFullAddress();

		} catch (UnknownHostException e) {
			System.out.println("Unable to start proxy (UnknownHostException)");
			return null;
		}

		ReferlProxy proxy = new ReferlProxy(eventDispatcher,
				Common.createRandomName(), address, Common.createLogHandlers());

		if (!proxy.start()) {
			System.out.println("Unable to start proxy");
			return null;
		}

		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				proxy.stop();
				process.stop();
				eventDispatcher.stop();				
			}
		});

		return new Pair<>(process,proxy);
	}

	public static String readFileContents(File f) throws FileNotFoundException {
		final Scanner sc = new Scanner(f);
		String content = sc.useDelimiter("\\Z").next();
		sc.close();
		
		return content;
		
	}
	
}
