package daruma.storage_manager.type_definition;

import daruma.storage_manager.type_definition.TypedInstance;
import daruma.storage_manager.type_definition.TypeException;
import daruma.storage_manager.StorageManager;

import daruma.sql.DatabaseConnection;
import daruma.sql.DatabaseConnectionException;

import java.sql.SQLException;


public class TypedInstanceSet
{
	private	TypeDefinition			type;
	private	DatabaseConnection.QueryResult	queryResult;
	private	StorageManager			storage;

	public	TypedInstanceSet( TypeDefinition  type ,
				  DatabaseConnection.QueryResult  queryResult ,
				  StorageManager  storage )
						    throws TypeException
	{
		this.type        = type;
		this.queryResult = queryResult;
		this.storage     = storage;
	}


	public	TypedInstance	getNextTypedInstance() throws TypeException
	{
		boolean	hasNext = false;

		try
		{
			hasNext = this.queryResult.next();
		}
		catch( DatabaseConnectionException e )
		{
			throw new TypeException( e );
		}

		if ( hasNext )
		{
			return( new TypedInstance( this.type ,
						   this.queryResult ,
						   this.storage ) );
		}
		else
		{
			return( null );
		}
	}


	public	void	close() throws TypeException
	{
		try
		{
			if ( this.queryResult != null )
			{
				this.queryResult.close();
			}
		}
		catch( DatabaseConnectionException  e )
		{
			throw new TypeException( e );
		}
	}
}
