
package org.eclipse.birt.test.performance;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.birt.core.archive.FileArchiveWriter;
import org.eclipse.birt.core.archive.IDocArchiveWriter;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunTask;

/**
 * RunThread - represent a thread to perform engine Run task
 */
public class RunThread extends Thread
{

	public static int rCount;
	public static List input;
	public static List output;
	public static IReportEngine engine;
	public static Map stats;

	private Semaphore semaphore;
	private String basePath;

	/**
	 * Constructor
	 * 
	 * @param threadName -
	 *            thread identifier, use to identify this thread
	 * @param semaphore -
	 *            semaphore instance, use to call back thread monitor
	 * @param basePath -
	 *            configured basePath to input and output folder
	 */
	public RunThread( String threadName, Semaphore semaphore, String basePath )
	{

		super( threadName );
		this.semaphore = semaphore;
		this.basePath = basePath;
	}

	public void run( )
	{

		try
		{
			long bTime;
			long eTime;

			for ( int i = 0; i < rCount; i++ )
			{
				// execution, task begin
				String inputStr = input.get( i ).toString( );
				String outputStr = output.get( i ).toString( );
				System.out.println( "begin " + inputStr ); //$NON-NLS-1$
				bTime = System.currentTimeMillis( );

				IReportRunnable runnable = engine.openReportDesign( basePath
						+ Constants.INPUT_PATH + inputStr );
				IRunTask task = engine.createRunTask( runnable );
				task.setAppContext( new HashMap( ) );
				IDocArchiveWriter archive = null;
				try
				{
					String targetFile = basePath + Constants.RUN_PATH
							+ outputStr + this.getName( ) + Constants.DOC_EXT;
					archive = new FileArchiveWriter( targetFile );
				}
				catch ( IOException e )
				{
					e.printStackTrace( );
				}
				task.run( archive );
				task.close( );

				// execution, task end
				eTime = System.currentTimeMillis( );
				System.out.println( "end " + inputStr ); //$NON-NLS-1$

				// record task time
				if ( stats != null )
				{
					stats.put( outputStr + "[thread" + this.getName( ) + "]", //$NON-NLS-1$//$NON-NLS-2$
							new Long( eTime - bTime ) );
				}
			}
			// stop semaphore
			semaphore.release( );
		}
		catch ( Exception e )
		{
			e.printStackTrace( );
			System.exit( -1 );
		}
	}
}