package jfractionlab.officeMachine;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

import javax.swing.JDialog;
import javax.swing.JOptionPane;

import jfractionlab.ConfManager;
import jfractionlab.JFractionLab;
import jfractionlab.jflDialogs.InfoDialog;


/**
 * 
 * @author jochen
 *
 * Before the OfficeMachine can be started, OfficeStarter has to check, if all the
 * needed libs are available. otherwise the VM will throw an Exception 
 * while reading all the import-statements of OfficeMachine
 */
public class OfficeStarter {

	public OfficeStarter(
			JDialog owner,
			File file,
			int type,
			int max1,
			int max2
	){
		if(setLibs()){
			if(checkOfficeInstallation()){
				JFractionLab.worksheetProcessIsOK = true;
				JOptionPane.showMessageDialog(null, lang.Messages.getString("wait_patiently"));
				new OfficeMachine(
						file,
						type,
						max1,
						max2
				);
				if(JFractionLab.worksheetProcessIsOK){
					//fixme on windows optionpane always in front
					JOptionPane.showMessageDialog(owner, lang.Messages.getString("worksheet_is_ready"));
				}
			}
		}
	}
	
	private boolean setLibs(){
		boolean bl = true;
		ConfManager cm = new ConfManager();
		String[] uno_jars = cm.getUnoConfJars();
		for(int i = 0; i < uno_jars.length; i++){
			try {
				OfficeStarter.addToClassPath(new File(uno_jars[i]));
			} catch (java.lang.Exception e) {
				bl = false;
				e.printStackTrace();
			}
		}
		if (!bl) JOptionPane.showMessageDialog(null, "Error setLibs");
		return bl;
	}
	
	private boolean checkOfficeInstallation(){
		boolean bl = true;
		String[] ar = new ConfManager().getUnoConfJars();
		for(int i = 0; i<ar.length;i++){
			if(!(new File(ar[i]).exists()) || ar[i].equals("") || ar[i].equals(null)){
				bl = false;
			}
		}
		if(bl){
			//conf auslesen
		}
		if (!bl){
			new InfoDialog(
					lang.Messages.getString("libreoffice_is_not_installed"),
					lang.Messages.getString("libreoffice_is_not_installed")+"<br><br>"+
					lang.Messages.getString("install_libreoffice")+"  ("+
					lang.Messages.getString("libreoffice_url")+")<br><br>"+
					lang.Messages.getString("you_have_to_configure_libreoffice")+"<br><br>"+
					lang.Messages.getString("please_use_office_configuration_dialog"),
					600, 400
			);
		}
		return bl;
	}
	
	public static void addToClassPath(File file) throws 
	IllegalArgumentException,
	IllegalAccessException,
	InvocationTargetException,
	SecurityException,
	NoSuchMethodException,
	IOException
{
	System.setProperty(
		"java.class.path",
		System.getProperty("java.class.path") + ":" + file.getCanonicalPath()
	);
	Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
	addURL.setAccessible(true);
	addURL.invoke(ClassLoader.getSystemClassLoader(), file.toURI().toURL());
}
}
