package siprp;

import siprp.companydataloaders.*;
import siprp.data.*;
import siprp.clientes.*;

import com.evolute.utils.*;
import com.evolute.utils.db.*;
import com.evolute.utils.db.keyretrievers.*;
import com.evolute.utils.error.*;
import com.evolute.utils.jdbc.*;
import com.evolute.utils.jdo.*;
import com.evolute.utils.sql.*;
import com.evolute.utils.ui.*;
import com.evolute.utils.ui.window.*;

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import siprp.update.UpdateWindow;

public class Main implements com.evolute.utils.ui.window.Connector
{
	public final static String SHST_VERSION = "7.8";
	
	private final static ClassLoader classLoader = new EVUtilsImageLib().getClass().getClassLoader();
	
	private static String dbase;
	private SIPRPTracker siprpTracker;
	
	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 );
	}
	
	public static void main( String args[] )
		throws Exception
	{
//		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 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-2006)" }, "",
				(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 );
		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" );
			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() );
			
//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();
		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 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 );
	}
}
