/*
 * NoticiasDataProvider.java
 *
 * Created on 24 de Maio de 2005, 15:39
 */

package siprp.clientes;

import com.evolute.utils.*;
import com.evolute.utils.arrays.*;
import com.evolute.utils.data.*;
import com.evolute.utils.db.*;
import com.evolute.utils.metadb.*;
import com.evolute.utils.ui.search.*;
import com.evolute.utils.sql.*;

import siprp.*;

/**
 *
 * @author  fpalma
 */
public class NoticiasDataProvider extends MetaProvider
{
	private static final Object LOCK = new Object();
	private static NoticiasDataProvider instance = null;
	private final Executer executer;
	
	/** Creates a new instance of NoticiasDataProvider */
	public NoticiasDataProvider()
		throws Exception
	{
		boolean webAware = ( ( Boolean ) Singleton.getInstance( SingletonConstants.WEB_AWARE ) ).booleanValue();
		DBManager dbm;
		if( webAware )
		{
			String url = ( String ) Singleton.getInstance( SingletonConstants.WEB_URL_PREFIX );
			url += ( String ) Singleton.getInstance( SingletonConstants.WEB_URL ) + "/";
			url += ( String ) Singleton.getInstance( SingletonConstants.WEB_DB_NAME ) + "/";
			String user = ( String ) Singleton.getInstance( SingletonConstants.WEB_USER );
			String pwd = ( String ) Singleton.getInstance( SingletonConstants.WEB_PASSWORD );
			dbm = new JDBCManager( url, user, pwd, 10, 8, 8, null );
			executer = dbm.getSharedExecuter( this );
		}
		else
		{
			dbm = null;
			executer = null;
		}
	}
	
	public static MetaProvider getProvider()
		throws Exception
	{
		synchronized( LOCK )
		{
			if( instance == null )
			{
				instance = new NoticiasDataProvider();
			}
		}
		return instance;
	}
	
	public String getNoticias()
		throws Exception
	{
		Select subSelect = 
			new Select( new String[]{ "not_noticias" },
						new String[]{ "MAX(id)" }, null );
						
		Select select = 
			new Select( new String[]{ "not_noticias" },
						new String[]{ "noticia" },
						new Field( "id" ).isEqual( subSelect ) );
		Virtual2DArray array = executer.executeQuery( select );
		if( array.columnLength() == 0 || array.get( 0, 0 ) == null )
		{
			return "";
		}
		return array.get( 0, 0 ).toString().trim();
	}
	
	public void saveNoticias( String noticias )
		throws Exception
	{
		
		
		Insert insert = 
			new Insert( "not_noticias",	
						new Assignment[]{ new Assignment( new Field( "utilizador" ), Singleton.getInstance( Singleton.USERNAME ) ),
											new Assignment( new Field( "data" ), Singleton.getInstance( Singleton.TODAY ) ),
											new Assignment( new Field( "noticia" ), noticias.trim() ) } );
		executer.executeQuery( insert );
	}
}
