package siprp;

import static siprp.ProcessoConstants.ESTADO_PROCESSO_BY_CODE;
import static siprp.ProcessoConstants.PROCESSO_ABERTO_CODE;
import static siprp.ProcessoConstants.PROCESSO_ABERTO_DESCRIPTION;
import static siprp.ProcessoConstants.PROCESSO_CANCELADO_CODE;
import static siprp.ProcessoConstants.PROCESSO_CANCELADO_DESCRIPTION;
import static siprp.ProcessoConstants.PROCESSO_FECHADO_CODE;
import static siprp.ProcessoConstants.PROCESSO_FECHADO_DESCRIPTION;

import java.awt.Color;
import java.awt.GraphicsEnvironment;
import java.util.Date;
import java.util.Properties;

import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;

import siprp.clientes.AvisosPanel;
import siprp.companydataloaders.SIPRPDataLoader;
import siprp.data.ActualizacaoSaveHandler;
import siprp.data.DisableDeleteHandler;
import siprp.data.EmpresaData;
import siprp.data.EstabelecimentoData;
import siprp.data.MarcacaoEmpresaData;
import siprp.data.MarcacaoEstabelecimentoData;
import siprp.data.MarcacaoSaveAndDeleteHandler;
import siprp.data.MarcacaoTrabalhadorData;
import siprp.data.TrabalhadorData;
import siprp.lembretes.LembretesDemon;
import siprp.update.UpdateWindow;

import com.evolute.utils.EVUtilsImageLib;
import com.evolute.utils.Singleton;
import com.evolute.utils.db.DBException;
import com.evolute.utils.db.DBManager;
import com.evolute.utils.db.JDBCManager;
import com.evolute.utils.db.keyretrievers.JDBCAutoKeyRetriever;
import com.evolute.utils.error.ErrorLogger;
import com.evolute.utils.jdbc.DBStatementExecuter;
import com.evolute.utils.jdbc.StatementExecuterFactory;
import com.evolute.utils.jdo.JDOObject;
import com.evolute.utils.jdo.JDOProvider;
import com.evolute.utils.sql.Insert;
import com.evolute.utils.sql.SQLQuery;
import com.evolute.utils.strings.UnicodeChecker;
import com.evolute.utils.ui.DialogException;
import com.evolute.utils.ui.window.LoginWindow;

public class Main implements com.evolute.utils.ui.window.Connector
{
	public final static String SHST_VERSION = "8.4";
	
	private final static ClassLoader classLoader = new EVUtilsImageLib().getClass().getClassLoader();
	
	private static String dbase;
	private SIPRPTracker siprpTracker;
	private static LoginWindow loginWindow;
	
	private static AvisosPanel avisos = null;
	
	static
	{
		JDOObject.registerOperationHandlerForClass( DisableDeleteHandler.INSTANCE, EmpresaData.class );
		JDOObject.registerOperationHandlerForClass( DisableDeleteHandler.INSTANCE, EstabelecimentoData.class );
		JDOObject.registerOperationHandlerForClass( DisableDeleteHandler.INSTANCE, TrabalhadorData.class );
		
		JDOObject.registerOperationHandlerForClass( ActualizacaoSaveHandler.INSTANCE, EmpresaData.class );
		JDOObject.registerOperationHandlerForClass( ActualizacaoSaveHandler.INSTANCE, EstabelecimentoData.class );
		JDOObject.registerOperationHandlerForClass( ActualizacaoSaveHandler.INSTANCE, TrabalhadorData.class );
		
		JDOObject.registerOperationHandlerForClass( MarcacaoSaveAndDeleteHandler.INSTANCE, MarcacaoEmpresaData.class );
		JDOObject.registerOperationHandlerForClass( MarcacaoSaveAndDeleteHandler.INSTANCE, MarcacaoEstabelecimentoData.class );
		JDOObject.registerOperationHandlerForClass( MarcacaoSaveAndDeleteHandler.INSTANCE, MarcacaoTrabalhadorData.class );
		
		ESTADO_PROCESSO_BY_CODE.put( PROCESSO_ABERTO_CODE, PROCESSO_ABERTO_DESCRIPTION );
		ESTADO_PROCESSO_BY_CODE.put( PROCESSO_FECHADO_CODE, PROCESSO_FECHADO_DESCRIPTION );
		ESTADO_PROCESSO_BY_CODE.put( PROCESSO_CANCELADO_CODE, PROCESSO_CANCELADO_DESCRIPTION );
	}
	
	public static void main( String args[] )
		throws Exception
	{
		UIManager.put( "TextField.inactiveForeground", UIManager.get( "TextField.foreground" ) );
		UIManager.put( "TextField.foreground", ColorUIResource.RED.darker() );
		
		UIManager.put( "TextArea.inactiveForeground", UIManager.get( "TextArea.foreground" ) );
		UIManager.put( "TextArea.foreground", ColorUIResource.RED.darker() );
		
		UIManager.put( "ComboBox.disabledForeground", UIManager.get( "ComboBox.foreground" ) );
		UIManager.put( "ComboBox.foreground", ColorUIResource.RED.darker() );

//		Singleton.setInstance( SingletonConstants.COMPANY_NAME, "Centro Cl\u00ednico Avenida" );
//		Singleton.setInstance( SingletonConstants.COMPANY_LOGO, "logo_evo.jpg" );
//		Singleton.setInstance( SingletonConstants.WEB_AWARE, Boolean.FALSE );
//		Singleton.setInstance( SingletonConstants.DB_NAME, "shst" );
		
//		Singleton.setInstance( SingletonConstants.COMPANY_NAME, "SIPRP - Sociedade Ib\u00e9rica de Preven\u00e7\u00e3o de Riscos Profissionais" );
//		Singleton.setInstance( SingletonConstants.COMPANY_LOGO, "logo_combo.jpg" );
//		Singleton.setInstance( SingletonConstants.WEB_AWARE, Boolean.TRUE );
//		Singleton.setInstance( SingletonConstants.LOCAL_DB_NAME, "siprp" );
		new SIPRPDataLoader().load();
//		new ClinicaAvenidaDataLoader().load();
//		new IBookDataLoader().load();
		
		dbase = (String)Singleton.getInstance( SingletonConstants.LOCAL_DB_NAME );
/*		Calendar cal = Calendar.getInstance();
		cal.set( 2004, 06, 14 );
		if( cal.before( Calendar.getInstance() ) )
		{
			com.evolute.utils.ui.DialogException.showException( new RuntimeException( "Unknown error ocurred." ) );
		}
		else
		{
*/			Insert.setDefaultKeyRetriever( JDBCAutoKeyRetriever.DEFAULT );
			String server = System.getProperty( "server.address" );
//			if( server == null )
//			{
//				server = "ws_fpalma";
//			}
//			
//			String user = "root";
//			String passwd = "UNIXLuvsU";
//			
//			DBManager dbm = new JDBCManager( "jdbc:mysql://" + server + "/" + dbase, 
//						user, passwd , 10, 8, 8, null );
			
			UnicodeChecker.setUseDoubleSlash( true );
//			Singleton.setInstance( Singleton.DEFAULT_DBMANAGER, dbm );

//			StatementExecuterFactory.initialize( 
//					new DBStatementExecuter( dbm.getSharedExecuter() ) );
//		}
//		FichaWindow window = new FichaWindow();
/*		window.setLogo( new ImageIcon( 
			new Main().getClass().getClassLoader().getResource( "logo/logo_w400.png" ) 
			).getImage() );*/
//		window.show();
		avisos = new AvisosPanel();
		String logoFileName = ( String ) Singleton.getInstance( SingletonConstants.COMPANY_LOGO );
		loginWindow = new LoginWindow( new Main(), /*"logo"+File.separator +*/ logoFileName,//"logo"+File.separator + "logo_w400.jpg", 
				new String[] { (String) Singleton.getInstance( SingletonConstants.SOFTWARE_NAME ) }, 
				new String[] { "Vers\u00E3o " + SHST_VERSION, "(EVOLUTE 2004-2008)" }, "",
				(String)Singleton.getInstance( SingletonConstants.LOCAL_USER ), 
				(String)Singleton.getInstance( SingletonConstants.LOCAL_PASSWORD ), avisos, false );
		loginWindow.setTitle( (String) Singleton.getInstance( SingletonConstants.SOFTWARE_NAME ) );
		JPanel left = loginWindow.getLeftPanel();
		left.setBackground( Color.white );
		GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
		loginWindow.setExtendedState(loginWindow.getExtendedState() | loginWindow.MAXIMIZED_BOTH);
		loginWindow.setVisible( true );
		SwingUtilities.invokeLater( new Runnable(){
			public void run()
			{
				loginWindow.expandAll();
			}
		} );
		
		new UpdateWindow().update();
	}
	
	public boolean connect( String user, String passwd )
	{
		try
		{
			// run initialization SQL
			SQLQuery initQuery[] = new SQLQuery[] {};
//			String server = System.getProperty( "server.address" );
			String server = null;
			if( server == null )
			{
				//server = "192.168.1.191";
				server = (String)Singleton.getInstance( SingletonConstants.LOCAL_URL );
//				server = "ws_fpalma";
			}
			String prefix = (String)Singleton.getInstance( SingletonConstants.LOCAL_URL_PREFIX );
			String url = prefix + server + "/" + dbase;
//			System.out.println( "url: " + url + " user: " + user + " ps: " + passwd );
			DBManager dbm = new JDBCManager( url, user, passwd , 10, 8, 8, null );
//			UnicodeChecker.setUseDoubleSlash( true );
			Singleton.setInstance( Singleton.DEFAULT_DBMANAGER, dbm );

			StatementExecuterFactory.initialize( 
					new DBStatementExecuter( dbm.getSharedExecuter() ) );
			initializeJPOX( url, user, passwd );
			StatementExecuterFactory.initialize( 
					new DBStatementExecuter( dbm.getSharedExecuter() ) );
			StatementExecuterFactory.initialize( 
				new DBStatementExecuter( dbm.getSharedExecuter() ) );
			Singleton.setInstance( Singleton.TODAY, new Date() );
			initializeCayenne( url, user, passwd);
			
//cleanData( dbm.getSharedExecuter() );
//msg( dbm.getSharedExecuter() );
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "N\u00E3o foi poss\u00EDvel estabelecer"
				+ " a liga\u00E7\u00E3o \u00E0 base de dados.", false );
			return false;
		}
		Singleton.setInstance( Singleton.USERNAME, user );
		try
		{
			ErrorLogger.initializeLogger( new SHSTLogger() );
		}
		catch( Exception ex )
		{
		}
		//Singleton.setInstance( Singleton.USERNAME, user );
		siprpTracker = new SIPRPTracker( avisos );
		
		avisos.refresh();
//		new Exception().printStackTrace();
//		try
//		{
//			Thread.sleep( 1000 );
//		}
//		catch( Exception ex ){}
//		new Exception().printStackTrace();
		LembretesDemon.go();
		return true;
	}
	
//	public static void reconnectJDO()
//	{
//		PersistenceManagerFactory pmf = ( PersistenceManagerFactory ) Singleton.getInstance( Singleton.DEFAULT_PERSISTENCE_MANAGER_FACTORY );
//		PersistenceManager pm = pmf.getPersistenceManager();
//		Singleton.setInstance( SingletonConstants.PERSISTENCE_MANAGER, pm );
//		com.evolute.utils.jdo.JDOObject.setPersistentManager( pm );
//	}
	
	public boolean disconnect()
	{
		if( siprpTracker.quit() )
		{
			siprpTracker = null;
			try
			{
				( ( DBManager )Singleton.getInstance( 
					Singleton.DEFAULT_DBMANAGER ) ).close();
				Singleton.clear();
			}
			catch( DBException ex )
			{
				DialogException.showException( ex );
			}
			return true;
		}
		return false;
	}
	
	public void executeAction( DefaultMutableTreeNode node )
	{
		try
		{
			siprpTracker.openWindow( ( String )node.getUserObject() );
		}
		catch( Exception ex )
		{
			DialogException.showException( ex );
		}
	}
	
	public void exit()
	{
		if( siprpTracker == null || siprpTracker.quit() )
		{
			System.exit( 0 );
		}
	}
	
	public MutableTreeNode getTree()
	{
		return siprpTracker.getRoot();
	}
	
	public void initializeCayenne(String url, String user, String password)
	{
		// TODO: override DB location, user and password
	}

	public void initializeJPOX(String url, String user, String password)
	{
		Date d = new Date();
		System.out.println( "INIT: " + d );
		
		
		Properties jpoxProps;
		jpoxProps = System.getProperties();//new Properties();
		// Set the PersistenceManagerFactoryClass to the TJDO class.
		jpoxProps.setProperty( "javax.jdo.PersistenceManagerFactoryClass",
			"org.jpox.PersistenceManagerFactoryImpl" );
		// Set the JDBC driver name.
		jpoxProps.setProperty( "javax.jdo.option.ConnectionDriverName", (String) Singleton.getInstance( SingletonConstants.LOCAL_DRIVER_NAME ) );
		jpoxProps.setProperty( "org.jpox.identifier.fullyQualifiedNames", "false" );
		// props.setProperty("com.triactive.jdo.transactionIsolation",
		// "read-uncommitted" );

		// Set the connection URL
//		jpoxProps.setProperty( "javax.jdo.option.ConnectionURL", "jdbc:informix-sqli://192.168.0.3:6666"
//			+ "/apdp_db:informixserver=server" );
		jpoxProps.setProperty( "javax.jdo.option.ConnectionURL", url );
		jpoxProps.setProperty( "javax.jdo.option.ConnectionUserName", user );
		jpoxProps.setProperty( "javax.jdo.option.ConnectionPassword", password );
//		jpoxProps.setProperty( "javax.jdo.option.IgnoreCache", "true" );
//		jpoxProps.setProperty( "javax.jdo.option.NonTransactionalRead", "true" );
		jpoxProps.setProperty( "javax.jdo.option.RetainValues", "true" );
		
		jpoxProps.setProperty( "org.jpox.autoCreateTables", "false" );
		jpoxProps.setProperty( "org.jpox.autoCreateSchema", "false" );
		jpoxProps.setProperty( "org.jpox.autoCreateConstraints", "false" );
		jpoxProps.setProperty( "org.jpox.validateTables", "false" );
		jpoxProps.setProperty( "org.jpox.validateConstraints", "false" );
		jpoxProps.setProperty( "org.jpox.autoStartMechanismMode", "Ignored" );
		jpoxProps.setProperty( "org.jpox.autoStartMechanism", "None" );

//		jpoxProps.setProperty( "javax.jdo.option.RetainValues", "true" );
//		jpoxProps.setProperty( "javax.jdo.option.Optimistic", "true" );
		
//		jpoxProps.setProperty( "org.jpox.identifier.defaultSchemaName", "informix" );
		jpoxProps.setProperty( "org.jpox.rdbms.CheckExistTablesOrViews", "false" );
		
		System.setProperty( "org.jpox.catalogName", (String)Singleton.getInstance( SingletonConstants.LOCAL_DB_NAME ) );
		System.setProperty( "org.jpox.schemaName", "" );
		
//		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory( jpoxProps );
////		pmf.setOptimistic( true );
//System.out.print( "Loading PM: " + new Date() );
//		//   ( ( PersistenceManagerFactoryImpl )pmf ).setTransactionIsolation( Connection.TRANSACTION_READ_UNCOMMITTED );
//		// Retrieve a PersistenceManager from the PersistenceManagerFactory.
//		PersistenceManager pm = pmf.getPersistenceManager();
//		JDOObject.setPersistentManager( pm );
//		Singleton.setInstance( Singleton.DEFAULT_PERSISTENCE_MANAGER_FACTORY, pmf );
//		Singleton.setInstance( SingletonConstants.PERSISTENCE_MANAGER, pm );
		JDOProvider jdoProvider = new JDOProvider( jpoxProps );
		Singleton.setInstance( Singleton.DEFAULT_JDO_PROVIDER, jdoProvider );
System.out.println( "PM done " + new Date() + "JDO: " + jdoProvider );
	}
}
