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

importPackage( java.util.regex );

( function()
{
	CKLANGTOOL.jpformat = function()
	{
	};

	function printObject( prefix, o )
	{
		var result = [];
		
		for ( var key in o )
		{
			var entry = o[ key ],
				entryName = prefix ? ( prefix + '.' + key ) : key;
			
			if ( typeof entry == 'object' )
				result.push( printObject( entryName, entry ) );
			else
				result.push( entryName + '=' + entry );
		}
		
		return result.join( '\r\n' );
	}
	
	function processFile( file )
	{
		var date = new Date(),
			licenseInfo = "# Copyright (c) 2003-" + date.getFullYear() + ", CKSource - Frederico Knabben. All rights reserved.\r\n# For licensing, see LICENSE.html or http://ckeditor.com/license\r\n\r\n";

		var result = CKLANGTOOL.loadLanguageFile( file );
		var fileInfo = CKLANGTOOL.analyzeLanguageFile( file );
		fileHeader = fileInfo.fileOverviewBlock.replace( /\{.*?\}/g, '' ).replace( /@fileOverview/g, '' ).replace(/\s*(\/)?\s*(\*)+(\/)?/g , '').replace(/\s+/g, ' ');

		return licenseInfo + '#' + fileHeader + '\r\n\r\n' + printObject( '', result.translation );
	}

	/**
	 * Returns an array with missing keys (already marked as //MISSING).
	 */

	CKLANGTOOL.jpformat.prototype =
	{
		run : function()
		{
			var children = CKLANGTOOL.languageDir.list();
			var errors, file, status = [];
			var foundFiles = false;
			var fileHeader = "";

			for ( var i = 0 ; i < children.length ; i++ )
			{
				if ( CKLANGTOOL.io.getExtension( children[ i ] ) != "js" )
					continue;

				file = new File( CKLANGTOOL.languageDir, children[ i ] );
				if ( file.isFile() )
				{
					print( "Processing " + file.getAbsolutePath() );
					
					CKLANGTOOL.io.saveFile( new File( CKLANGTOOL.destinationDir, children[i].replaceAll( '.js', '.txt' ) ), processFile(file), false );
					
					foundFiles = true;
				}
			}

			if ( !foundFiles )
			{
				print( "WARNING: language files not found." );
			}

			print( "Process completed." );
		}
	};
})();
