/*
 * Updater.java
 *
 * Created on 26 de Setembro de 2006, 11:49
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package siprp.update;

import java.util.*;

import com.evolute.utils.*;
import com.evolute.utils.arrays.*;
import com.evolute.utils.db.*;
import com.evolute.utils.sql.*;


/**
 *
 * @author fpalma
 */
public class UpdateList
{
	protected static final Update UPDATE_LIST[] = 
			new Update[]{ new siprp.update.updates.V6_1_To_V7_0(), new siprp.update.updates.V7_0_To_V7_2(),
							new siprp.update.updates.V7_2_To_V7_4(), new siprp.update.updates.V7_4_To_V7_5(),
							new siprp.update.updates.V7_5_To_V7_6(), new siprp.update.updates.V7_6_To_V7_7() };
	
	protected static Executer EXECUTER;
	protected static double version = -1;
	
	/** Creates a new instance of Updater */
	private UpdateList()
	{
	}
	
	public static double getCurrentVersion()
		throws Exception
	{
		if( version < 0 )
		{
			version = getVersion();
		}
		return version;
	}
	
	public static Update []getUpdates()
		throws Exception
	{
		if( version < 0 )
		{
			version = getVersion();
		}
		Vector validUpdates = new Vector();
		for( int n = 0; n < UPDATE_LIST.length; n++ )
		{
			if( version <= UPDATE_LIST[ n ].getStartVersion() )
			{
				validUpdates.add( UPDATE_LIST[ n ] );
			}
		}
		return ( Update [] ) validUpdates.toArray( new Update[ validUpdates.size() ] );
	}
	
	protected static double getVersion()
		throws Exception
	{
		DBManager dbm = ( DBManager ) Singleton.getInstance( Singleton.DEFAULT_DBMANAGER );
		EXECUTER = dbm.getSharedExecuter();
		try
		{
			return readVersion();
		}
		catch( Exception ex )
		{
			createVersionTable();
		}
		return readVersion();
	}
	
	protected static double readVersion()
		throws Exception
	{
		Select select = 
				new Select( new String[]{ "version" },
							new String[]{ "MAX(current_version)" },
							null );
		Virtual2DArray array = EXECUTER.executeQuery( select );
		return ( ( Number ) array.get( 0, 0 ) ).doubleValue();
	}
	
	protected static void createVersionTable()
		throws Exception
	{
		com.evolute.utils.sql.Update update = 
				new com.evolute.utils.sql.Update( "CREATE TABLE version( current_version float );" );
		EXECUTER.executeQuery( update );
		Insert insert = 
				new Insert( "version",
							new Assignment[]{ 
								new Assignment( new Field( "current_version" ), new Double( 0.1 ) ) } );
		EXECUTER.executeQuery( insert );
	}
}
