/*
Copyright (c) 2003-2011, 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 );
importClass( java.util.Scanner );

/*
 * 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.ckpoformat' );
CKLANGTOOL.load( 'cklangtool.includes.po_parser' );
CKLANGTOOL.load( 'cklangtool.includes.io' );

if ( !arguments[0] || arguments[0] == '-help' || arguments[0] == '/?' )
	error( 'Usage: ' + command + ' command lang_dir dest_dir'
			+ '\n\nCKLangTool corrects translation files and creates report about missing translations.'

			+ '\n\nCommands:'
			+ '\nupdate  Update editor\'s language files (editor\'s "lang" folder) with new text entries from translation files with specified format.'
			+ '\noutput  Export editor\'s language files (editor\'s "lang" folder) to translation files with specified format.'

			+ '\n\nOptions:'
			+ '\n[-f|--format]=json|gettext|jprops  Format of language file when update from or export translation entries to, default to json.'
			+ '\n\t json - A private JavaScript format used as runtime language files in CKEditor.'
			+ '\n\t getext - The versatile GNU Gettext format, simplified to fit for CKEditor.'
			+ '\n\t jprops - The Java Properties file format.'
		   + '\n[-m|--metafile]=path  Specify the path to an optional meta file which used only by the Gettext format for context information.'
			+ '\n' );

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

function error( msg )
{
	System.err.println( msg );
	quit();
}

var arg, action, match, langDir, dstDir;
for ( var i = 0 ; i < arguments.length ; i++ )
{
	var arg = arguments[ i ];
	// Absorb sub command as first arg.
	if ( !i )
		action = arg;
	else
	{
		// Parse options.
		if ( match = arg.match( /^(?:-f|--format)=(.*?)$/ ) )
			CKLANGTOOL.format = match[ 1 ];
		else if ( match = arg.match( /^(?:-m|--metafile)=(.*?)$/ ) )
		{
			CKLANGTOOL.metaFile = new File( match[ 1 ] );
			if ( !CKLANGTOOL.metaFile.exists() )
				error( 'Meta file does not exist: ' + CKLANGTOOL.metaFile.getAbsolutePath() );
		}
		else if ( !langDir )
		{
			langDir = new File( arg );
			if ( !langDir.exists() )
				error( 'Specified language directory not exist: ' + langDir.getAbsolutePath() );

			CKLANGTOOL.languageDir = langDir;
			CKLANGTOOL.templateFile = new File( langDir, 'en.js' );
			if ( !CKLANGTOOL.templateFile.exists() )
				error( 'ERROR: The english language file "en.js" was not found (' + CKLANGTOOL.templateFile.getAbsolutePath() + ')' );
		}
		else if ( !dstDir )
		{
			dstDir = new File( arg );

			if ( !dstDir.isDirectory() )
				dstDir.mkdir();
			else if ( action == 'export' && dstDir.exists() )
			{
				var console = new Scanner( System[ 'in' ] );
				print( 'Destination directory already exists, overwrite? [y/n]' );
				var answer = console.next();
				if ( answer == 'y' )
					dstDir[ 'delete' ]();
				else
					quit();
			}

			CKLANGTOOL.destinationDir = dstDir;
		}
	}
}

// Command arguments validation.
if ( !( action in { 'update' : 1, 'export' : 1 } )
		|| !CKLANGTOOL.languageDir
		|| action == 'export' && !CKLANGTOOL.destinationDir )
	error( 'Bad arguments: "' + arguments.join( ' ' ) +'", check help for usage.' );

// Update from languages files.
if ( action == 'update' )
{
	var translator = new CKLANGTOOL.translator();
	translator.run( CKLANGTOOL.destinationDir || CKLANGTOOL.languageDir );
}
// Export translations to other formats.
else if ( action == 'export' )
{
	var formatter = CKLANGTOOL[ CKLANGTOOL.format ];
	if ( !formatter )
		error( 'Output language files in ' + CKLANGTOOL.format + ' format is not supported.' );
	new formatter().run();
}
