package tim.mkgmapgui;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * Gui wrapper for calling mkgmap (available separately)
 */
public class MkgmapGui
{

	/**
	 * @param args command line arguments
	 */
	public static void main(String[] args)
	{
		String jarloc = null;
		if (args != null && args.length > 0) {
			if (args.length == 1) {
				jarloc = args[0];
			}
			else {
				// Complain about too many arguments given
				System.err.println("Too many arguments given, expected at most one!\nUsage: java -jar mkgmapgui.jar [mkgmap.jar]");
			}
		}
		File mkgmapJar = findMkgmapJar(jarloc);
		if (mkgmapJar == null || !mkgmapJar.exists() || !mkgmapJar.canRead()) {
			System.err.println("Could not find mkgmap jar file");
		}
		else {
			launchMkgmap(mkgmapJar);
		}
	}

	/**
	 * Find the mkgmap jar either in the specified location or in the current directory
	 * @param inLoc optional path to mkgmap.jar file
	 * @return File where jar file found, or null
	 */
	private static File findMkgmapJar(String inLoc)
	{
		if (inLoc != null) {
			File specifiedFile = new File(inLoc);
			// If it's a direct link to the jar then great!
			if (checkFile(specifiedFile)) {return specifiedFile;}
			// If it's a directory then search through it
			if (specifiedFile.exists() && specifiedFile.isDirectory())
			{
				File foundFile = findMkgmapJar(specifiedFile);
				if (foundFile != null) {return foundFile;}
			}
		}
		// Now check in curent directory
		return findMkgmapJar(new File("").getAbsoluteFile());
	}

	/**
	 * Find the Mkgmap jar in the specified directory
	 * @param inDirectory directory to look in
	 * @return File if found, or null
	 */
	private static File findMkgmapJar(File inDirectory)
	{
		if (inDirectory != null && inDirectory.exists() && inDirectory.isDirectory())
		{
			File[] files = inDirectory.listFiles();
			for (int i=0; i<files.length; i++) {
				if (checkFile(files[i])) {
					return files[i];
				}
			}
		}
		// not found
		return null;
	}

	/**
	 * Check the given file to see if it is acceptable
	 * @param inFile File to check
	 * @return true if file is an acceptable mkgmap jar file
	 */
	private static boolean checkFile(File inFile)
	{
		return (inFile != null && inFile.exists() && inFile.isFile() && inFile.canRead()
			&& inFile.getName().toLowerCase().startsWith("mkgmap")
			&& inFile.getName().toLowerCase().endsWith(".jar"));
	}

	/**
	 * Launch the Mkgmap program
	 * @param inMkgmapJar jar file for mkgmap
	 */
	private static void launchMkgmap(File inMkgmapJar)
	{
		try
		{
			URLClassLoader cl = new URLClassLoader(new URL[] {inMkgmapJar.toURI().toURL()});
			GuiWindow window = new GuiWindow(cl);
			window.showDialog();
		}
		catch (MalformedURLException e) {
			System.err.println("Failed to load Jar: " + e.getMessage());
		}
	}
}
