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

package siprp.update;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

import com.evolute.utils.*;
import com.evolute.utils.date.*;
import com.evolute.utils.db.*;
import com.evolute.utils.sql.*;
import com.evolute.utils.ui.*;


/**
 *
 * @author fpalma
 */
public class UpdateWindow extends JFrame
		implements ActionListener
{
	protected JTextArea logText;
	protected JButton closeButton;	
	
	protected Update updates[];
	protected String filename;
	
	public static void main( String args[] )
	{
		UpdateWindow updateWindow = new UpdateWindow();
		updateWindow.update();
	}
	
	/** Creates a new instance of UpdateWindow */
	public UpdateWindow()
	{
		setupComponents();
	}
	
	private void setupComponents()
	{
		setTitle( "Actualiza\u00e7\u00e3o do Software" );
		setSize( 800, 600 );
		logText = new JTextArea();
		logText.setLineWrap( true );
		logText.setWrapStyleWord( true );
		logText.setEditable( true );
		JScrollPane scp = 
				new JScrollPane( logText, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
									JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		closeButton = new JButton( "Fechar" );
		
		setLayout( new BorderLayout() );
		add( scp, BorderLayout.CENTER );
		add( closeButton, BorderLayout.SOUTH );
	
		closeButton.setEnabled( false );
		closeButton.addActionListener( this );
		
		setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
	}
	
	public void actionPerformed( ActionEvent e )
	{
		Object source = e.getSource();
		if( source.equals( closeButton ) )
		{
			close();
		}
	}
	
	public void close()
	{
		SwingUtilities.invokeLater( new Runnable(){
			public void run()
			{
				setVisible( false );
				dispose();
			}
		} );
	}
	
	public void update()
	{
		log( "A verificar a exist\u00eancia de actualiza\u00e7\u00f5es...\n" );
		try
		{
			double version = UpdateList.getCurrentVersion();
			log( "Vers\u00e3o actual: " + ( version < 6.1 ? 6.1 : version ) + "\n" );
			updates = UpdateList.getUpdates();
		}
		catch( Exception ex )
		{
			setVisible( true );
			log( "Erro a verificar actualiza\u00e7\u00f5es!!!" );
			ex.printStackTrace();
			updates = new Update[ 0 ];
		}
		if( updates.length > 0 )
		{
			setVisible( true );
			log( "Existe " + ( updates.length >  1 ? "m " : " " ) + updates.length + 
							" actualiza\u00e7" + ( updates.length >  1 ? "\u00f5es... " : "\u00e3o\n" ) );
			boolean ok = doUpdates();
			if( ok )
			{
				log( "**** Actualiza\u00e7\u00f5es terminadas ****\n" );
			}
			else
			{
				log( "**** Actualiza\u00e7\u00f5es abortadas ****\n" );
				log( "\nPode favor contacte a EVOLUTE\n" );
			}
			
		}
		closeButton.setEnabled( true );
	}
	
	protected void log( final String newLog )
	{
		SwingUtilities.invokeLater( new Runnable(){
			public void run()
			{
				logText.append( newLog );
			}
		} );
	}
	
	protected boolean doUpdates()
	{
		double last = 0.1;
		log( "**** A realizar actualiza\u00e7\u00f5es... **** \n" );
		for( int n = 0; n < updates.length; n++ )
		{
			last = updates[ n ].getEndVersion();
			String msg = "  " + updates[ n ] + "... \n";
			String changes[] = updates[ n ].listChanges();
			for( int c = 0; c < changes.length; c++ )
			{
				msg += "     " + changes[ c ] + "\n";
			}
			log( msg );
			try
			{
				updates[ n ].doUpdate();
			}
			catch( Exception ex )
			{
				log( "ERRO ! ! !\nA abortar actualiza\u00e7\u00f5es\n" );
				ex.printStackTrace();
				return false;
			}
		}
		try
		{
			DBManager dbm = ( DBManager ) Singleton.getInstance( Singleton.DEFAULT_DBMANAGER );
			Executer executer = dbm.getSharedExecuter();
			com.evolute.utils.sql.Update update = 
					new com.evolute.utils.sql.Update( "version",
							new Assignment[]{ 
								new Assignment( new Field( "current_version" ), new Double( last ) ) },
							null );
			executer.executeQuery( update );
			log( "Vers\u00e3o actualizada para: " + last + "\n" );
			return true;
		}
		catch( Exception ex )
		{
			log( "ERRO ! ! !\nA abortar actualiza\u00e7\u00f5es\n" );
			ex.printStackTrace();
			return false;
		}	
	}
	
	public int getUpdateCount()
	{
		return updates.length;
	}
}
