package daruma.sql;

// XXX: should be an abstract class ?
public class SQLDataType
{
	// XXX: should be abstract method of DatabaseConnection?
	private static final int	INDEX_LENGTH = 128;

	private	String	sqlBaseDataTypeName;
	private	String	sqlRetrieveFunction;
	private	Class	javaClass;

	public	SQLDataType( String  sqlBaseDataTypeName ,
			     String  sqlRetrieveFunction ,
			     Class  javaClass )
	{
		this.sqlBaseDataTypeName = sqlBaseDataTypeName;
		this.sqlRetrieveFunction = sqlRetrieveFunction;
		this.javaClass           = javaClass;
	}

	public	SQLDataType( String  sqlBaseDataTypeName ,
			     Class  javaClass )
	{
		this.sqlBaseDataTypeName = sqlBaseDataTypeName;
		this.sqlRetrieveFunction = null;
		this.javaClass           = javaClass;
	}

	public	String	getSQLBaseDataTypeString()
	{
		return( this.sqlBaseDataTypeName );
	}

	public	String	getSQLRetrieveColumnString( String  columnName )
	{
		if ( this.sqlRetrieveFunction != null )
		{
		    return this.sqlRetrieveFunction + "_" + columnName;
		}
		else
		{
			return( columnName );
		}
	}

	public	String	getSQLRetrieveColumnStringForRawSQLString
							( String  columnName )
	{
		if ( this.sqlRetrieveFunction != null )
		{
			return( this.sqlRetrieveFunction
				+ "(" + columnName + ")"
				+ " AS " + this.sqlRetrieveFunction
				+ "_" + columnName );
		}
		else
		{
			return( columnName );
		}
	}

	public	String	getIndexString( String  columnName )
	{
		if ( this.needsIndexLength() )
		{
			return( "INDEX(" + columnName + "("
				+ SQLDataType.INDEX_LENGTH + "))" );
		}
		else
		{
			return( "INDEX(" + columnName + ")" );
		}
	}

	private	boolean	needsIndexLength()
	{
		return( (this.sqlBaseDataTypeName.equals( "blob" )
		      || this.sqlBaseDataTypeName.equals
			 ( SQLDataTypeConstant.BLOB
			   .getSQLBaseDataTypeString() )
		      || this.sqlBaseDataTypeName.equals( "geometry" )) );
	}

	public	boolean	isTimeFamilyType()
	{
		return( this.sqlBaseDataTypeName.equals( "timestamp" )
		     || this.sqlBaseDataTypeName.equals( "datetime" ) );
	}

	private	boolean	isSpatialType()
	{
		return( this.sqlBaseDataTypeName.equals( "geometry" ) );
	}

	/*
	public	boolean	isNotNull()
	{
	}
	*/

	// XXX: boolean needQuotes() or escapeValue( String  value ) etc...

	public	Class  getJavaClass()
	{
		return( this.javaClass );
	}
}
