/*******************************************************************************
 * 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.chart.ui.swt.wizard.internal;

import java.util.ArrayList;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Text;

/**
 * 
 */

public class DataDefinitionTextManager
{

	private static DataDefinitionTextManager instance;
	private ArrayList textCollection = null;

	private DataDefinitionTextManager( )
	{
		textCollection = new ArrayList( );
	}

	public synchronized static DataDefinitionTextManager getInstance( )
	{
		if ( instance == null )
			instance = new DataDefinitionTextManager( );
		return instance;
	}

	public void addDataDefinitionText( Text text )
	{
		textCollection.add( text );
	}

	public void removeDataDefinitionText( Text text )
	{
		textCollection.remove( text );
	}

	public void removeAll( )
	{
		textCollection.clear( );
	}

	public void refreshAll( )
	{
		checkAll( );
		int length = textCollection.size( );
		for ( int i = 0; i < length; i++ )
		{
			Text current = ( (Text) textCollection.get( i ) );
			if ( current.getText( ).length( ) > 0 )
			{
				Color color = ColorPalette.getInstance( )
						.getColor( current.getText( ) );
				current.setBackground( color );
			}
		}
	}

	/**
	 * Checks all texts and removes disposed controls
	 * 
	 */
	private void checkAll( )
	{
		int length = textCollection.size( );
		for ( int i = 0; i < length; )
		{
			Text current = ( (Text) textCollection.get( i ) );
			if ( current.isDisposed( ) )
			{
				textCollection.remove( i );
				length--;
			}
			else
			{
				i++;
			}
		}
	}

	public int getNumberOfSameDataDefinition( String expression )
	{
		checkAll( );
		int number = 0;
		int length = textCollection.size( );
		for ( int i = 0; i < length; i++ )
		{
			Text current = ( (Text) textCollection.get( i ) );
			if ( current.getText( ).equals( expression ) )
			{
				number++;
			}
		}
		return number;
	}
}
