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.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Date;

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 org.apache.cayenne.access.DataDomain;
import org.apache.cayenne.access.DataNode;
import org.apache.cayenne.conf.DefaultConfiguration;
import org.apache.cayenne.conn.DriverDataSource;
import org.apache.cayenne.dba.AutoAdapter;
import org.apache.cayenne.map.DataMap;

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.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 = "11.2.2";
	
	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;
	public static File fopConfigFile;
	
	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", ColorUIResource.BLACK );
		UIManager.put( "TextField.foreground", ColorUIResource.RED.darker() );
		
		UIManager.put( "TextArea.inactiveForeground", ColorUIResource.BLACK );
		UIManager.put( "TextArea.foreground", ColorUIResource.RED.darker() );
		
		UIManager.put( "ComboBox.disabledForeground", ColorUIResource.BLACK );
		UIManager.put( "ComboBox.foreground", ColorUIResource.RED.darker() );
		
		UIManager.put( "FormattedTextField.inactiveForeground", ColorUIResource.BLACK );
		UIManager.put( "FormattedTextField.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 );
//		dbase = "siprp_local3";
/*		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-2009)" }, "",
				(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();
			}
		} );

		fopConfigFile = loadFopConfigFile();
		
		new UpdateWindow().update();
	}
	
	
	private static File loadFopConfigFile() {

		try {
			InputStream is = ClassLoader.getSystemClassLoader()
					.getResourceAsStream("siprp/util/fop/fop.xconf");
			if (is != null) {
				File tempFile = File.createTempFile("fop", ".xconf");
				FileOutputStream fos = new FileOutputStream(tempFile);
				byte[] buf = new byte[256];
				int read = 0;
				while ((read = is.read(buf)) > 0) {
					fos.write(buf, 0, read);
				}
				return tempFile;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public boolean connect( String user, String passwd )
	{
		String url = null;
		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 = "storage";
//				server = "ws_fpalma";
			}
			String prefix = (String)Singleton.getInstance( SingletonConstants.LOCAL_URL_PREFIX );
			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() ) );
			new JDOInitializer().initializeJDO( 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.\n(" +url+ ")", 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) throws SQLException
	{
		DataDomain domain = DefaultConfiguration.getSharedConfiguration().getDomain();
		DataMap map = domain.getMap( "SIPRPMap" );
		DriverDataSource dataSource = new DriverDataSource((String) Singleton.getInstance( SingletonConstants.LOCAL_DRIVER_NAME ), url, user, password );
		DataNode node = new DataNode("SIPRPNode");
		node.setDataSource( dataSource );
		node.setAdapter( new AutoAdapter(dataSource) );
		node.addDataMap( map );
		node.setEntityResolver( domain.getEntityResolver() );
		domain.reset();
		domain.addNode( node );
	}
	
}
