/*
 *  Draco Econometrics
 *  Copyright (C) 2008-2009 Approximatrix, LLC
 *  http://www.approximatrix.com
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

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();
		}
	}
	
}
