package com.approximatrix.draco.application.plugin;

import java.util.List;
import java.util.Vector;

import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;

public class PluginRegistry extends Vector<Plugin> {

	private static final String SCRIPT_REGISTRY_BEAN = "registry";
	private static final String SCRIPT_DIRECTORY_BEAN = "directories";
	
	private static final String EXPRESSION_LANG = "ruby";
	private static final String EXPRESSION_SCRIPT = "load '/pengine/register.rb'";
	
	private BSFManager manager = null;
	
	public PluginRegistry() {
		manager = new BSFManager();
	}
	
	public void register(List<String> directories) {
		
		try {
			manager.declareBean(SCRIPT_REGISTRY_BEAN, this, PluginRegistry.class);
			manager.declareBean(SCRIPT_DIRECTORY_BEAN, directories, List.class);
			manager.exec(EXPRESSION_LANG, "(java)", 1, 1, EXPRESSION_SCRIPT);
		} catch(BSFException be) {
			System.err.println("Error performing plugin registration...");
			be.printStackTrace();
		} finally {
			cleanupRegistrationBeans();
		}
	}
	
	private void cleanupRegistrationBeans() {
		try {
			manager.undeclareBean(SCRIPT_REGISTRY_BEAN);
			manager.undeclareBean(SCRIPT_DIRECTORY_BEAN);
		} catch(BSFException be) {
			System.err.println("Error cleaning up BSF beans during Plugin registration...");
			be.printStackTrace();
		}
	}
	
}
