/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

package org.eclipse.birt.data.engine.executor.transform.group;

import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.odi.IQuery.GroupSpec;

/**
 * Interval range implementation of GroupBy, which does grouping in such a
 * column which data type is String.
 */
class GroupByStringRange extends GroupBy
{

	/** prefix string length */
	private int prefixLen;

	/**
	 * @param prefixLen
	 */
	GroupByStringRange( GroupSpec groupDefn )
	{
		this.prefixLen = (int) groupDefn.getIntervalRange( );
	}

	/*
	 * @see org.eclipse.birt.data.engine.api.IGroupExtraInfo#isWithinSameGroup(java.lang.Object,
	 *      java.lang.Object)
	 */
	boolean isSameGroup( Object currentGroupKey, Object previousGroupKey )
			throws DataException
	{
		assert ( currentGroupKey != null );
		assert ( previousGroupKey != null );

		boolean isSame = false;
		String prevStr = (String) previousGroupKey;
		String currStr = (String) currentGroupKey;

		if ( prefixLen < 1 )
		{
			isSame = currStr.equals( prevStr );
		}
		else
		{
			if ( currStr.equals( prevStr ) )
			{
				isSame = true;
			}
			else
			{
				if ( currStr.length( ) < prefixLen
						|| prevStr.length( ) < prefixLen )
				{
					isSame = false;
				}
				else
				{
					String subStr1 = currStr.substring( 0, prefixLen );
					String subStr2 = prevStr.substring( 0, prefixLen );
					isSame = subStr1.equals( subStr2 );
				}
			}
		}
		return isSame;
	}

}