/*
 *************************************************************************
 * 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.aggregation;

import java.util.HashSet;
import java.util.Set;

import org.eclipse.birt.data.engine.api.aggregation.Accumulator;
import org.eclipse.birt.data.engine.api.aggregation.IAggregation;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;

/**
 * Implements the built-in Total.countDistinct aggregation
 */
class TotalCountDistinct implements IAggregation
{
    public String getName()
    {
        return BuiltInAggregationFactory.TOTAL_COUNTDISTINCT_FUNC;
    }
    
    public int getType()
    {
        return SUMMARY_AGGR;
    }
    
    public boolean[] getParameterDefn()
    {
        // 1 argument 
        final boolean paramDefn[] = { true };
        return paramDefn;
    }
    
    public Accumulator newAccumulator()
    {
        return new MyAccumulator();
    }
    
    private class MyAccumulator extends SummaryAccumulator
    {
        private Set set;
        private boolean hasNullValue = false;
        
        public void start()
        {
            super.start();
            set = new HashSet();
        }
        
        public void onRow( Object[] args ) throws DataException
        {
        	assert(args.length>0);
        	if(args[0] instanceof Comparable)
        	{
        		set.add(args[0]);
        	}
        	else
        	{
        		if( args[0] == null )
        		{
        			this.hasNullValue = true;
        		}
        		else
        		{
        			throw new DataException( ResourceConstants.UNSUPPORTED_DATA_TYPE,
        				args[0]==null?null:args[0].getClass().getName() );
        		}
        	}
        }


        /* (non-Javadoc)
         * @see org.eclipse.birt.data.engine.aggregation.SummaryAccumulator#getSummaryValue()
         */
        public Object getSummaryValue()
        {
            return new Integer( set.size( ) + ( this.hasNullValue ? 1 : 0 ) );
        }
    }
}
