package com.approximatrix.draco.general.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;

import com.approximatrix.draco.application.ApplicationManager;
import com.approximatrix.draco.application.plugin.Plugin;
import com.approximatrix.draco.application.plugin.PluginData;
import com.approximatrix.draco.application.plugin.PluginType;
import com.approximatrix.draco.application.plugin.ui.PluginErrorDialog;
import com.approximatrix.draco.application.plugin.ui.PluginWindow;
import com.approximatrix.draco.main.ui.DataDialog;

public class PluginMenuHandler implements ActionListener {

	private DataDialog parent = null;
	
	public PluginMenuHandler(DataDialog parent) {
		this.parent = parent;	
	}
	
	public List<JMenuItem> getRegressionPluginMenuItems() {
		return getMenuItemsOfType(PluginType.regression);
	}
	
	public List<JMenuItem> getAnalysisPluginMenuItems() {
		return getMenuItemsOfType(PluginType.analysis);
	}
	
	private List<JMenuItem> getMenuItemsOfType(PluginType type) {
		List<JMenuItem> ret = new ArrayList<JMenuItem>();
		for(Plugin plugin : getListOfType(type)) {
			JMenuItem one = new PluginMenuItem(plugin);
			one.addActionListener(this);
			ret.add(one);
		}
		return ret;
	}
	
	private List<Plugin> getListOfType(PluginType type) {
		List<Plugin> ret = new ArrayList<Plugin>();
		
		for(Plugin pi : ApplicationManager.GetPluginRegistry()) {
			if(pi.getType().equals(type))
				ret.add(pi);
		}
		return ret;
	}

	public void actionPerformed(ActionEvent e) {
		if(!(e.getSource() instanceof PluginMenuItem)) 
			return;
		
		PluginMenuItem pluginItem = (PluginMenuItem)e.getSource();
		final Plugin topass = pluginItem.getPlugin();
		
		new GeneralWorker(this.parent.getMainWindow(),
				"Initializing Plugin","Starting "+pluginItem.getText(),
				new GeneralWorker.WorkRoutine() {
					public void doWork() {
						
						try {
							final Plugin worker = topass.createInstance();
							worker.initialize(parent.getDataModel());
							SwingUtilities.invokeLater(new Runnable() {
								public void run() {
									parent.getMainWindow().openWindow(new PluginWindow(worker,parent.getDataModel()));
								}
							});
							
						} catch(Exception e) {
							
							final Exception tpe = e;
							SwingUtilities.invokeLater(new Runnable() {
								public void run() {
									new PluginErrorDialog(parent.getMainWindow(),tpe).setVisible(true);
								}
							});
							
						}
						
					}
				});
		
	}
	
	public class PluginMenuItem extends JMenuItem {

		private Plugin plugin = null;
		
		public PluginMenuItem(Plugin relatedPlugin) {
			super(relatedPlugin.getName());
			
			if(!super.getText().endsWith("..."))
				super.setText(relatedPlugin.getName()+"...");
			
			plugin = relatedPlugin;
		}
		
		public Plugin getPlugin() {
			return plugin;
		}
		
	}
	
	
}
