
package org.eclipse.birt.report.model.api;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.structures.CachedMetaData;
import org.eclipse.birt.report.model.api.elements.structures.ResultSetColumn;
import org.eclipse.birt.report.model.api.metadata.PropertyValueException;
import org.eclipse.birt.report.model.api.util.CompaibilityUtil;
import org.eclipse.birt.report.model.util.BaseTestCase;

/**
 * 
 */

public class CompaitibiltyUtilTest extends BaseTestCase
{

	/**
	 * @throws Exception
	 */

	public void testUpdateCachedMetaDataResultSet( ) throws Exception
	{
		createDesign( );

		ScriptDataSetHandle setHandle = designHandle.getElementFactory( )
				.newScriptDataSet( "dataset1" ); //$NON-NLS-1$

		// no cached meta data.

		List columns = createResultColumns( );

		CompaibilityUtil.updateResultSetinCachedMetaData( setHandle, columns );

		CachedMetaDataHandle cachedMeta = setHandle.getCachedMetaDataHandle( );
		assertNotNull( cachedMeta );

		List newColumns = (List) cachedMeta.getResultSet( ).getValue( );
		assertEquals( 2, newColumns.size( ) );

		// try failed cases.

		columns.clear( );

		columns.add( StructureFactory.createColumnHint( ) );
		try
		{
			CompaibilityUtil.updateResultSetinCachedMetaData( setHandle,
					columns );
			fail( );
		}
		catch ( SemanticException e )
		{
			assertEquals(
					PropertyValueException.DESIGN_EXCEPTION_WRONG_ITEM_TYPE, e
							.getErrorCode( ) );
		}

		columns.clear( );

		columns.add( StructureFactory.createResultSetColumn( ) );
		try
		{
			CompaibilityUtil.updateResultSetinCachedMetaData( setHandle,
					columns );
			fail( );
		}
		catch ( SemanticException e )
		{
			assertEquals(
					PropertyValueException.DESIGN_EXCEPTION_VALUE_REQUIRED, e
							.getErrorCode( ) );
		}

		// has cached metadata already.

		cachedMeta.setProperty( CachedMetaData.RESULT_SET_MEMBER, null );

		columns = createResultColumns( );
		CompaibilityUtil.updateResultSetinCachedMetaData( setHandle, columns );

		newColumns = (List) cachedMeta.getResultSet( ).getValue( );
		assertEquals( 2, newColumns.size( ) );

	}

	private List createResultColumns( )
	{
		List columns = new ArrayList( );
		ResultSetColumn column = StructureFactory.createResultSetColumn( );
		column.setColumnName( "column1" );
		column.setPosition( new Integer( 1 ) );
		columns.add( column );

		column = StructureFactory.createResultSetColumn( );
		column.setColumnName( "column2" );
		column.setPosition( new Integer( 2 ) );
		columns.add( column );

		return columns;
	}
}
