
package org.eclipse.birt.tests.data.engine.regression;

import org.eclipse.birt.data.engine.api.IResultIterator;
import org.eclipse.birt.data.engine.api.querydefn.OdaDataSetDesign;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;

import testutil.APITestCase;
import testutil.ConfigText;

/**
 * <b>Regression test case description:</b>
 * <p>
 * row[0] doesnt work anymore to retrieve the row count
 * </p>
 * <b>Test description:</b>
 * <p>
 * We has use 2 column bindings expression to test identify of row[0] and
 * row["__rownum"] Compare it with golden.
 * </p>
 */

public class Regression_138777 extends APITestCase
{

	String callsTableName;

	protected void setUp( ) throws Exception
	{
		super.setUp( );

		prepareDataSet( new DataSourceInfo( ConfigText
				.getString( "Api.TestData0.TableName" ), ConfigText
				.getString( "Api.TestData0.TableSQL" ), ConfigText
				.getString( "Api.TestData0.TestDataFileName" ) ) );

		callsTableName = ConfigText.getString( "Api.TestData0.TableName" );
	}

	/*
	 * @see org.eclipse.birt.data.engine.api.APITestCase#getDataSourceInfo()
	 */
	protected DataSourceInfo getDataSourceInfo( )
	{
		return new DataSourceInfo( ConfigText
				.getString( "Api.TestData0.TableName" ), ConfigText
				.getString( "Api.TestData0.TableSQL" ), ConfigText
				.getString( "Api.TestData0.TestDataFileName" ) );
	}

	public void testRowNum( ) throws Exception
	{
		String testSQL = "select " + callsTableName + ".AMOUNT1 " + "from "
				+ callsTableName;

		( (OdaDataSetDesign) this.dataSet ).setQueryText( testSQL );

		String[] bindingNameRow = new String[3];
		bindingNameRow[0] = "ROW_AMOUNT1";
		bindingNameRow[1] = "ROW_NUM";
		bindingNameRow[2] = "ROW_NUM1";
		ScriptExpression[] bindingExprRow = new ScriptExpression[]{

		new ScriptExpression( "dataSetRow.AMOUNT1" ),
				new ScriptExpression( "row.__rownum" ),
				new ScriptExpression( "row[0]" )};

		IResultIterator resultIt = this.executeQuery( this.createQuery( null,
				null, null, null, null, null, null, null, null, bindingNameRow,
				bindingExprRow ) );

		printResult( resultIt, bindingNameRow, bindingExprRow );
		checkOutputFile( );

	}

	private void printResult( IResultIterator resultIt,
			String[] bindingNameRow, ScriptExpression[] bindingExprRow )
			throws Exception
	{
		// output column name
		String str = "";
		for ( int i = 0; i < bindingNameRow.length; i++ )
		{
			str += bindingExprRow[i].getText( ).replaceAll(
					"dataSetRow\\Q.\\E", "" );
			str += "  ";
		}
		testPrintln( str );

		// output row data
		while ( resultIt.next( ) )
		{
			str = "";
			for ( int i = 0; i < bindingNameRow.length; i++ )
			{
				str += " ";
				if ( resultIt.getValue( bindingNameRow[i] ) == null )
					str += "<null>";
				else
					str += (int) Double.parseDouble( resultIt.getValue(
							bindingNameRow[i] ).toString( ) );
				str += "    ";
			}
			testPrintln( str );
		}
	}
}