package net.oni2.aeinstaller.backend.oni;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Vector;

import org.apache.commons.io.FileUtils;

import net.oni2.aeinstaller.backend.CaseInsensitiveFile;
import net.oni2.aeinstaller.backend.Paths;
import net.oni2.platformtools.PlatformInformation;
import net.oni2.platformtools.PlatformInformation.Platform;
import net.oni2.platformtools.applicationinvoker.ApplicationInvoker;
import net.oni2.platformtools.applicationinvoker.EExeType;
import net.oni2.platformtools.applicationinvoker.ERuntimeNotInstalledException;

/**
 * @author Christian Illy
 */
public class OniLauncher {

	private static File getOniExe() throws FileNotFoundException {
		File exe = null;
		switch (PlatformInformation.getPlatform()) {
			case WIN:
			case LINUX:
				exe = new File(Paths.getEditionBasePath(), "Oni.exe");
				break;
			case MACOS:
				exe = new File(Paths.getEditionBasePath(),
						"Oni.app/Contents/MacOS/Oni");
				break;
			default:
		}
		if (exe.exists())
			return exe;
		else
			throw new FileNotFoundException("Oni's executable was not found");
	}

	private static EExeType getOniExeType() {
		switch (PlatformInformation.getPlatform()) {
			case MACOS:
				return EExeType.OSBINARY;
			default:
				return EExeType.WINEXE;
		}
	}
	
	private static Vector<String> getLaunchArgs () {
		Vector<String> res = new Vector<String>();
		if (PlatformInformation.getPlatform() == Platform.MACOS) {
			File launchArgs = CaseInsensitiveFile.getCaseInsensitiveFile(Paths.getEditionBasePath(), "launch_args.txt");
			if (launchArgs.exists()) {
				try {
					String[] argsStrings = FileUtils.readFileToString(launchArgs).split(" ");
					for (int i = 0; i < argsStrings.length; i++) {
						argsStrings [i] = argsStrings [i].trim();
						if (argsStrings [i].length() > 0) {
							res.add(argsStrings [i]);
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return res;
	}

	/**
	 * @param windowed
	 *            Run in windowed mode
	 * @throws FileNotFoundException
	 *             If Oni's executable was not found
	 * @throws ERuntimeNotInstalledException
	 *             If Linux and Wine not found
	 */
	public static void launch(boolean windowed) throws FileNotFoundException,
			ERuntimeNotInstalledException {
		File exe = getOniExe();
		Vector<String> params = getLaunchArgs();
		params.add("-debugfiles");
		if (windowed)
			params.add("-noswitch");
		else
			params.remove("-noswitch");
		ApplicationInvoker.execute(getOniExeType(), Paths.getEditionBasePath(),
				exe, params, true);
	}

}
