package com.businesslogic.ireport.ui;

import com.businesslogic.ireport.*;
import com.ms.wfc.app.*;
import com.ms.wfc.core.*;
import com.ms.wfc.ui.*;
import com.ms.wfc.html.*;
import java.util.*;

/**
 * Questa classe può accettare un numero variabile di parametri sulla riga
 * di comando. L'esecuzione del programma inizia con il metodo main(). Il costruttore
 * della classe non viene richiamato fino a quando un oggetto di tipo "JasperReportForm"
 * non viene creato nel metodo main().
 */
public class JasperReportForm extends Form implements Runnable
{
	Thread t = null;
	MainForm mf;
	public JasperReportForm(MainForm mf)
	{
		super();

		// Necessario per il supporto della finestra di progettazione form di Visual J++
		initForm();		
		t = new Thread(this);
		// TODO: aggiungere il codice del costruttore dopo la chiamata di initForm.
		/*
		String cp="";
		cp = ".;";
		String jasperlib = "C:\\Documenti\\progetti\\iReport\\jasperreports-0.4.1-project\\JasperReports\\lib\\";
		cp += jasperlib + "jasperreports.jar;";
		cp += jasperlib + "commons-beanutils.jar;";
		cp += jasperlib + "commons-collections.jar;";
		cp += jasperlib + "commons-digester.jar;";
		cp += jasperlib + "itext-0.92.jar;";
		cp += jasperlib + "xerces.jar;";
		cp += "C:\\jdk1.3.1\\lib\\tools.jar;";
		cp += jasperlib + "interclient.jar;";
		cp += jasperlib + "jdom.jar;";
		cp += ";"+ com.ms.wfc.io.File.getCurrentDirectory() ;
		cp += ";"+  mf.programDir;
		cp += ";"+"C:\\Documenti\\progetti\\Infosys\\WGInstaller";
		*/
		//MessageBox.show(  +"\n"+com.ms.wfc.io.File.getCurrentDirectory());
					
		//ClasspathForm.SetEnvironmentVariable("CLASSPATH",cp);
		
		this.mf = mf;	
		comboBoxExport.setSelectedIndex(1);
	}
	
	public void fillConnectionCombo(Vector v)
	{
		comboBoxConnection.removeAll();
		if (v == null) return;
		Enumeration enum = v.elements();
		comboBoxConnection.addItem("No connection");
		comboBoxConnection.setSelectedIndex(0);
		while (enum.hasMoreElements())
		{
			comboBoxConnection.addItem( enum.nextElement() );
		}
		
	}
	
	public void setFileName(String f)
	{
		editInFile.setText(f); 
	}
	
	public void setQuery(String f)
	{
		editQuery.setText(f); 
	}
	
	public void run()
	{
		String ext = "";
		editOutput.setText("");
		String cmd = com.ms.wfc.io.File.combine( (String) mf.connProperties.get("JAVA_HOME") , "bin\\java.exe") + " -Dorg.xml.sax.driver=org.apache.xerces.parsers.SAXParser IReportCompiler -c ";
		if (comboBoxExport.getSelectedIndex()==1)
		{
			ext = "pdf";
			cmd +=" -pdf ";
		}
		else if (comboBoxExport.getSelectedIndex()==2)
		{
			ext = "html";
			cmd +=" -html ";
		}
		else if (comboBoxExport.getSelectedIndex()==3)
		{
			ext = "xls";
			cmd +=" -xls ";
		}
		else if (comboBoxExport.getSelectedIndex()==4)
		{
			ext = "csv";
			cmd +=" -csv ";
		}
		
		if (comboBoxConnection.getSelectedIndex() != 0)
		{
			ConnectionEntry ce = (ConnectionEntry)comboBoxConnection.getSelectedItem();
			cmd +=" -jdriver" + ce.driverClass +" -juser"+ce.username+" -jpasswd"+ce.password+" -jurl"+ce.url;
		}
		
		if (mf.ireportProperties.getProperty("COMPILER_OUT_DIR") != null &&
			mf.ireportProperties.getProperty("COMPILER_OUT_DIR").length() > 0)
		{
			cmd += " -outdir\""+mf.ireportProperties.getProperty("COMPILER_OUT_DIR")+"\" ";
		}
		
		if (editQuery.getText().length()>0)
		{
			cmd += " -query \""+ editQuery.getText() +"\" ";
		}
										
		cmd += " \""+editInFile.getText()+"\" ";
		if (execute(cmd,true) == 0)
		{
			if (comboBoxExport.getSelectedIndex()>0)
			{
				
				String pdfFileName = editInFile.getText().substring(0,editInFile.getText().length()-3)+ext;
				if (mf.ireportProperties.getProperty("COMPILER_OUT_DIR") != null &&
					mf.ireportProperties.getProperty("COMPILER_OUT_DIR").length() > 0)
				{
						pdfFileName = com.ms.wfc.io.File.combine(mf.ireportProperties.getProperty("COMPILER_OUT_DIR"),
											com.ms.wfc.io.File.getName(pdfFileName));
				}
				editOutput.setText( editOutput.getText()+"\r\nViewing "+ ext +"..."+pdfFileName);
				com.ms.win32.Shell32.ShellExecute( 0, 
									   "open", 
									   pdfFileName,"","",
									   com.ms.win32.wins.SW_SHOWNORMAL);	
			}
		}
		else
		{
			editOutput.setText( editOutput.getText()+"\r\nAbnormal termination!");
		}
		//cmd = ;
		//execute(cmd);
		button2.setText("Compile");
	}
	
	// Execute program...
	public int execute(String cmd, boolean wait)
	{
		
		int ret = 0;
		try {
				java.lang.Runtime rt = java.lang.Runtime.getRuntime();
				java.lang.Process p = rt.exec( cmd);
				//java.io.InputStream is = p.getErrorStream();
				java.io.InputStream is2 = p.getInputStream();
				
				int b;
				long count;
				count = 0;
				String row="";
				editOutput.setText(editOutput.getText()+"\r\n"+cmd+"\r\n"+row);
				while ((b=is2.read()) != -1)
				{
					if (b != '\n')
					{
						row += new String(new byte[]{(byte)b});
					}
					else 
					{
						editOutput.setText( editOutput.getText()+"\r\n"+row);
						row="";
					}
				}
				//is.close();
				is2.close();
				if (wait)
					ret = p.waitFor();
			} catch (Exception ex)
			{
				ret = -1;
				//
				
				MessageBox.show("An error occurred executing file \n"+ cmd.substring(0,cmd.indexOf("java.exe")+8)+"\n"+"- Check that this file exists\n- Check the java home in Database->classpath dialog and set java home\n   to a value like: C:\\jdk1.3.1");
			}
			
		return ret;
	}

	/**
	 * JasperReportForm esegue l'overriding di dispose e quindi può svuotare
	 * l'elenco dei componenti.
	 */
	public void dispose()
	{
		super.dispose();
		components.dispose();
	}

	private void button3_click(Object source, Event e)
	{
		if (t!=null)
			t.stop();
		this.dispose();
	}

	private void button1_click(Object source, Event e)
	{
		OpenFileDialog ofd = new OpenFileDialog();
		ofd.setCheckFileExists(true);
		ofd.setFilter("Jasper XML Report *.xml|*.xml");
		ofd.setDefaultExt("xml");
		int result = ofd.showDialog();
		if (result == DialogResult.OK)
		{
			editInFile.setText(ofd.getFileName());
		}
		
	}

	private void button2_click(Object source, Event e)
	{
		if (button2.getText().equals("Compile"))
		{
			if ((String)mf.ireportProperties.getProperty("COMPILER_SAVE") == null ||
			mf.ireportProperties.getProperty("COMPILER_SAVE").equalsIgnoreCase("true"))
			{
				// Save report...
				mf.saveReport( this.editInFile.getText());
			}
				
			t = new Thread(this);
			button2.setText("Stop");
			t.start();
		}
		else
		{
			button2.setText("Compile");
			t.stop();
		}
		
	}

	private void panel2_paint(Object source, PaintEvent e)
	{
		
	}

	

	private void comboBoxExport_selectedIndexChanged(Object source, Event e)
	{
		
	}

	/**
	 * NOTA: il seguente codice è richiesto dalla finestra di progettazione form 
	 * di Visual J++. È possibile modificarlo con l'Editor di form.  Non modificarlo
	 * con l'Editor del codice.
	 */
	Container components = new Container();
	Edit editOutput = new Edit();
	Panel panel1 = new Panel();
	Panel panel2 = new Panel();
	Button button1 = new Button();
	Edit editInFile = new Edit();
	Button button2 = new Button();
	Label label2 = new Label();
	Button button3 = new Button();
	Label label1 = new Label();
	ComboBox comboBoxConnection = new ComboBox();
	Label label3 = new Label();
	Edit editQuery = new Edit();
	ComboBox comboBoxExport = new ComboBox();

	private void initForm()
	{
		// REMARQUE : cette feuille stocke des informations sur les ressources
		// dans un fichier externe. Ne modifiez le paramètre de chaîne d'aucun
		// appel de fonction resources.getObject(). Par exemple,
		// ne modifiez pas "foo1_location" dans la ligne de code
		// suivante, même si le nom de l'objet Foo change : 
		//	 foo1.setLocation((Point)resources.getObject("foo1_location"));

		IResourceManager resources = new ResourceManager(this, "JasperReportForm");
		this.setText("iReport Compiler Tool");
		this.setAutoScaleBaseSize(new Point(5, 13));
		this.setClientSize(new Point(587, 304));
		this.setIcon((Icon)resources.getObject("this_icon"));

		editOutput.setBackColor(Color.INACTIVEBORDER);
		editOutput.setDock(ControlDock.FILL);
		editOutput.setFont(new Font("Monospac821 BT", 8.0f, FontSize.POINTS, FontWeight.BOLD, false, false, false, CharacterSet.DEFAULT, 0));
		editOutput.setLocation(new Point(0, 104));
		editOutput.setSize(new Point(587, 168));
		editOutput.setTabIndex(1);
		editOutput.setText("");
		editOutput.setMultiline(true);
		editOutput.setReadOnly(true);
		editOutput.setScrollBars(ScrollBars.BOTH);

		panel1.setDock(ControlDock.BOTTOM);
		panel1.setLocation(new Point(0, 272));
		panel1.setSize(new Point(587, 32));
		panel1.setTabIndex(2);
		panel1.setText("panel1");

		panel2.setDock(ControlDock.TOP);
		panel2.setSize(new Point(587, 104));
		panel2.setTabIndex(0);
		panel2.setText("panel2");
		panel2.addOnPaint(new PaintEventHandler(this.panel2_paint));

		button1.setLocation(new Point(492, 4));
		button1.setSize(new Point(88, 24));
		button1.setTabIndex(2);
		button1.setText("Select XML file...");
		button1.addOnClick(new EventHandler(this.button1_click));

		editInFile.setLocation(new Point(84, 8));
		editInFile.setSize(new Point(404, 20));
		editInFile.setTabIndex(1);
		editInFile.setText("");

		button2.setLocation(new Point(8, 4));
		button2.setSize(new Point(92, 24));
		button2.setTabIndex(0);
		button2.setText("Compile");
		button2.addOnClick(new EventHandler(this.button2_click));

		label2.setLocation(new Point(8, 12));
		label2.setSize(new Point(72, 16));
		label2.setTabIndex(6);
		label2.setTabStop(false);
		label2.setText("Input file name");
		label2.setTextAlign(HorizontalAlignment.RIGHT);

		button3.setAnchor(ControlAnchor.BOTTOMRIGHT);
		button3.setLocation(new Point(504, 4));
		button3.setSize(new Point(80, 24));
		button3.setTabIndex(1);
		button3.setText("Close");
		button3.addOnClick(new EventHandler(this.button3_click));

		label1.setLocation(new Point(8, 32));
		label1.setSize(new Point(72, 16));
		label1.setTabIndex(0);
		label1.setTabStop(false);
		label1.setText("Connection");
		label1.setTextAlign(HorizontalAlignment.RIGHT);

		comboBoxConnection.setLocation(new Point(84, 32));
		comboBoxConnection.setSize(new Point(212, 21));
		comboBoxConnection.setTabIndex(3);
		comboBoxConnection.setText("");
		comboBoxConnection.setStyle(ComboBoxStyle.DROPDOWNLIST);

		label3.setLocation(new Point(24, 60));
		label3.setSize(new Point(52, 16));
		label3.setTabIndex(7);
		label3.setTabStop(false);
		label3.setText("Query SQL");

		editQuery.setLocation(new Point(84, 56));
		editQuery.setSize(new Point(492, 40));
		editQuery.setTabIndex(5);
		editQuery.setText("");
		editQuery.setMultiline(true);

		comboBoxExport.setLocation(new Point(300, 32));
		comboBoxExport.setSize(new Point(276, 21));
		comboBoxExport.setTabIndex(4);
		comboBoxExport.setText("");
		comboBoxExport.setStyle(ComboBoxStyle.DROPDOWNLIST);
		comboBoxExport.setItems(new Object[] {
								"Compile only", 
								"Compile and  preview as PDF exported report", 
								"Compile and  preview as HTML exported report", 
								"Compile and  preview as XLS exported report", 
								"Compile and  preview as CVS exported report"});
		comboBoxExport.addOnSelectedIndexChanged(new EventHandler(this.comboBoxExport_selectedIndexChanged));

		this.setNewControls(new Control[] {
							panel2, 
							panel1, 
							editOutput});
		panel1.setNewControls(new Control[] {
							  button3, 
							  button2});
		panel2.setNewControls(new Control[] {
							  comboBoxExport, 
							  label1, 
							  comboBoxConnection, 
							  editQuery, 
							  label3, 
							  button1, 
							  label2, 
							  editInFile});
	}

	/**
	 * Punto di ingresso principale per l'applicazione. 
	 *
	 * @param args Matrice di parametri passata all'applicazione
	 * tramite la riga di comando.
	 */
	public static void main(String args[])
	{
		Application.run(new JasperReportForm(null));
	}
}
