/*
 * Menu: Experimental > Generate ScriptDoc Binary
 * Kudos: Ingo Muschenetz
 * License: EPL 1.0
 * DOM: http://download.eclipse.org/technology/dash/update/org.eclipse.eclipsemonkey.lang.javascript
 */
 
 // includes
include("lib/IDE_Utils.js");

/**
 * @param args
 */
function main()
{
 	// make sure we have access to the JS editor bundle
	loadBundle("com.aptana.ide.editor.js");
	
 	var Environment = Packages.com.aptana.ide.editor.js.runtime.Environment;
 	var NativeObjectsReader2 = Packages.com.aptana.ide.editor.scriptdoc.parsing.reader.NativeObjectsReader2;
 	var File = Packages.java.io.File;
 	var InputStream = Packages.java.io.InputStream;
 	var FileOutputStream = Packages.java.io.FileOutputStream;
 	var FileInputStream = Packages.java.io.FileInputStream;
 	var TabledOutputStream = Packages.com.aptana.ide.io.TabledOutputStream;

	// grab the file from the current editor
	var inputFilename = getFilename();
	
	if (inputFilename != null)
	{
		if (inputFilename.match(/\.xml$/i))
		{
			var inputFile = new File(inputFilename);
			
			if (inputFile.exists())
			{
				var binaryFilePath = inputFilename + ".bin"
				var binaryFile = new File(binaryFilePath);
				
				if (binaryFile.exists() == false || binaryFile.canWrite())
				{
					// Create the base JavaScript environment
					var environment = new Environment();
					environment.initBuiltInObjects();
					var reader = new NativeObjectsReader2(environment);
					var input = new FileInputStream(inputFile);
				
					// Load in the XML file
					out.println("Reading Documentation " + inputFilename);
					reader.loadXML(input);
				
					// Read the file and write out the stream
					var outputStream = new FileOutputStream(binaryFile);
					var output = new TabledOutputStream(outputStream);
					reader.getScriptDoc().write(output);
				
					// close the output stream and refresh file in project view
					output.close();
					refresh(binaryFilePath);
					
					// write that we are done
					out.println("Conversion complete.");
					out.println("Saved as file " + inputFilename + ".bin");
					out.println();
				}
				else
				{
					out.println("Output file " + binaryFilePath + " is not writable.");
				}
			}
			else
			{
				out.println("Input file " + inputFilename + " does not exist. You may need to save your file before proceeding.");
			}
		}
		else
		{
			out.println("Input file must be an XML file.");
		}
	}
	else
	{
		out.println("Unable to retrieve active editor's file name.");
	}
}