/*
Copyright (c) 2003-2009, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
 */

importPackage( org.mozilla.javascript );
importClass( java.lang.System );
importClass( java.io.File );

/*
 * Check if we're running the compiled version of this script. If yes, the
 * langtool class should be available.
 */
var isCompiled = true;
var command = "java -cp js.jar org.mozilla.javascript.tools.shell.Main langtool.js";
var resource = JavaAdapter( org.mozilla.javascript.Parser )["class"].getResource( "/org/mozilla/javascript" ).toString();

try
{
	java.lang.Class.forName( "cklangtool.langtool" );
}
catch ( e )
{
	isCompiled = false;
}

var cklangtoolPath = '';

if ( isCompiled )
{
	var quit = function()
	{
		System.exit( 0 );
	};

	loadClass( 'cklangtool.includes.cklangtool' );

	var resource = JavaAdapter( org.mozilla.javascript.Parser )["class"].getResource( "/org/mozilla/javascript" ).toString();
	if ( resource.indexOf( ".exe" ) )
		command = "langtool.exe";
	else
		command = "java -jar langtool.jar";
}
else
{
	cklangtoolPath = resource.replaceFirst( "^jar:", '' ).replaceFirst( "\/js\.jar\!\/org\/mozilla\/javascript$", '' )
			.replaceAll( "_dev.{1}_thirdparty.{1}rhino", "" );

	load( cklangtoolPath + "_source/includes/cklangtool.js" );

	CKLANGTOOL.path = cklangtoolPath;
}

CKLANGTOOL.isCompiled = isCompiled;
CKLANGTOOL.load( 'cklangtool.includes.ckjpformat' );
CKLANGTOOL.load( 'cklangtool.includes.io' );

if ( !arguments[0] || arguments[0] == '-help' || arguments[0] == '/?' )
	error( 'Usage: ' + command + ' lang_dir [-jpformat=dest_dir]'
			+ '\n\n CKLangTool corrects translation files and creates report about missing translations.'
			+ '\n\n -jpformat  Convert files to java properties format and save them in dest_dir.\n' );

for ( var i = 0 ; i < arguments.length ; i++ )
{
	if ( arguments[i].indexOf( "-jpformat=" ) != -1 )
	{
		var destDir = arguments[i].substring( arguments[i].indexOf( "=" ) + 1 );
		CKLANGTOOL.destinationDir = new File( destDir );
		if ( CKLANGTOOL.destinationDir.exists() )
			error( 'Destination directory already exists: ' + CKLANGTOOL.destinationDir.getAbsolutePath() );
		else
			CKLANGTOOL.destinationDir.mkdir();
		CKLANGTOOL.operation = "jpformat";
	}
}

if ( arguments[0] == '-test' && !isCompiled )
{
	CKLANGTOOL.load( 'test.test' );
	quit();
}

CKLANGTOOL.languageDir = new File( arguments[0] );
CKLANGTOOL.templateFile = new File( arguments[0], 'en.js' );

if ( !CKLANGTOOL.templateFile.exists() )
{
	error( 'ERROR: The english language file "en.js" was not found (' + CKLANGTOOL.templateFile.getAbsolutePath() + ')' );
}

function error( msg )
{
	print( msg );
	print( '' );
	quit();
}

( function()
{
	try
	{
		if ( CKLANGTOOL.operation == "jpformat" )
		{
			var jpformat = new CKLANGTOOL.jpformat();
			jpformat.run();
		}
		else
		{
			var translator = new CKLANGTOOL.translator();
			translator.run();
		}
	}
	catch ( e )
	{
		print( "" );
		error( e );
	}
} )();
