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

CKPACKAGER.load( 'ckpackager.includes.packagefile' );

CKPACKAGER.packager = function()
{
	this.packageFiles = [];
};

CKPACKAGER.packager.prototype =
{
	loadDefinitionFile : function( filePath )
	{
		var file = new File( filePath );

		// Evaluate the package definition, moving its contents to CKPACKAGER.packDefinition.
		var packCode = 'var pack = { ' + CKPACKAGER.tools.readFile( file ) + '\n};';

		var cx = Context.enter(),
			scope = cx.initStandardObjects();

		try
		{
			cx.evaluateString( scope, packCode, file.getName(), 1, null );
		}
		catch ( e )
		{
			if ( CKPACKAGER.verbose && typeof ( e.rhinoException ) != 'undefined' )
				e.rhinoException.printStackTrace();

			error( '\nParsing package file failed:\n    Error: ' + e.message + '\n    File: ' + file.getAbsolutePath()
					+ '\n    Line: ' + e.lineNumber );
		}

		this.loadDefinition( scope.pack );
	},

	loadDefinition : function( definitionObject )
	{
		var packages = definitionObject.packages;

		if ( packages )
		{
			for ( var i = 0 ; i < packages.length ; i++ )
			{
				var packDefinition = packages[ i ];

				if ( !packDefinition.output )
					error( 'The "output" value must be set for all packages in the packager defintion file(' + CKPACKAGER.packFile + ').' );

				var packFile = new CKPACKAGER.packageFile( CKPACKAGER.getOutputPath( packDefinition.output ) );

				if ( definitionObject.header )
					packFile.header = definitionObject.header;

				if ( typeof definitionObject.noCheck != 'undefined' )
					packFile.noCheck = definitionObject.noCheck;

				if ( definitionObject.constants )
					packFile.constants = definitionObject.constants;

				if ( typeof packDefinition.renameGlobals != 'undefined' )
					packFile.renameGlobals = packDefinition.renameGlobals;

				if ( typeof packDefinition.compactJavascript != 'undefined' )
					packFile.compactJavascript = packDefinition.compactJavascript;

				if ( typeof packDefinition.wrap != 'undefined' )
					packFile.wrap = packDefinition.wrap;

				var files = packDefinition.files;

				if ( files )
				{
					for ( var f = 0 ; f < files.length ; f++ )
						packFile.files.push( CKPACKAGER.getPackPath( files[ f ] ) );
				}

				this.packageFiles.push( packFile );
			}
		}
	},

	run : function()
	{
		var time = new Date();

		for ( var i = 0 ; i < this.packageFiles.length ; i++ )
		{
			this.packageFiles[ i ].createFile();
		}

		time = ( new Date() ) - time;
		time = time / 1000;

		switch ( this.packageFiles.length )
		{
			case 0 :
				print( 'No files defined' );
				break;
			case 1 :
				print( 'The generation of the package file has been completed in ' + time + ' seconds.' );
				break;
			default :
				print( 'The generation of ' + this.packageFiles.length + ' files has been completed in ' + time + ' seconds.' );
				break;
		}

		print( '' );
	}
};
