package daruma.storage_manager.type_definition.types;

import daruma.storage_manager.type_definition.AbstractSingleTypeDefinition;
import daruma.storage_manager.type_definition.TypeException;
import daruma.sql.SQLDataType;
import daruma.sql.SQLDataTypeConstant;

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

public class StringTypeDefinition extends AbstractSingleTypeDefinition
{
	private	long		minLength = -1;
	private	long		maxLength = -1;
	private	Set<String>	enumerationSet = null;

	public	StringTypeDefinition()
	{
		super();
	}

	@Override
	public	SQLDataType	getSingleSQLDataType()
	{
		return( SQLDataTypeConstant.BLOB );
	}

	@Override
	public	String	parseValue( String  value ) throws TypeException
	{
		if ( this.minLength != -1
		  && value.length() < this.minLength )
		{
			throw new TypeException( "too short string \""
						 + value + "\"" );
		}
		else if ( this.maxLength != -1
		       && value.length() > this.maxLength )
		{
			throw new TypeException( "too long string \""
						 + value + "\"" );
		}
		else if ( this.enumerationSet != null
		       && ! this.enumerationSet.contains( value ) )
		{
			throw new TypeException( "value \"" + value + "\""
						 + " is not a valid member"
						 + " of enumeration set" );
		}

		return( value );
	}


	//
	// string type dependents
	//
	public	void	setMinLength( long  limit )
	{
		assert limit >= 0;

		this.minLength = limit;
	}

	public	void	setMaxLength( long  limit )
	{
		assert limit >= 0;

		this.maxLength = limit;
	}

	public	void	addEnumeration( String  value )
	{
		if ( this.enumerationSet == null )
		{
			this.enumerationSet = new HashSet<String>();
		}

		this.enumerationSet.add( value );
	}

	public	StringTypeDefinition	deepCopy()
	{
		StringTypeDefinition	ret = new StringTypeDefinition();

		ret.minLength = this.minLength;
		ret.maxLength = this.minLength;

		if ( this.enumerationSet != null )
		{
			ret.enumerationSet
				= new HashSet<String>( this.enumerationSet );
		}

		return( ret );
	}
}
