/*
 *  Draco Econometrics
 *  Copyright (C) 2006-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.editor.wizard;

import java.io.IOException;
import java.io.InputStream;

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

import com.approximatrix.draco.application.plugin.Plugin;

public class PluginCreatorController {

	private static final String BUILDER_INIT_SCRIPT = "/templates/builder_init.rb";
	private static final String BUILDER_DATA_BEAN = "data";
	private static final String PLUGIN_LANG = "ruby";
	
	private PluginWizardData data = null;
	private BSFManager manager = null;
	private String result = null;
	
	public PluginCreatorController(PluginWizardData data) {
		this.data = data;
		this.manager = new BSFManager();
		this.result = null;
	}
	
	private String loadScript() throws IOException {
		InputStream is = Plugin.class.getResourceAsStream(BUILDER_INIT_SCRIPT);
		StringBuffer buffer = new StringBuffer();
		int b;
		while((b = is.read())>0) {
			buffer.append((char)b);
		}
		is.close();
		return buffer.toString();
	}
	
	public void runCreator() {
		IPluginCreator obj = null;
    	try {
			manager.declareBean(BUILDER_DATA_BEAN, this.data, PluginWizardData.class);
			obj = (IPluginCreator)manager.eval(PLUGIN_LANG, "(java)", 1, 1, loadScript());
			this.result = obj.getPluginText();
		} catch(BSFException be) {
			System.err.println("Error performing plugin builder initialization...");
			be.printStackTrace();
		} catch(ClassCastException cce) {
			System.err.println("Unexpected object returned during plugin builder initialization.");
		} catch(IOException ioe) {
			System.err.println("Error loading plugin builder initialization script: "+BUILDER_INIT_SCRIPT);
		} finally {
			try {
				manager.undeclareBean(BUILDER_DATA_BEAN);
			} catch(BSFException be) {
				System.err.println("Error cleaning up BSF beans during Plugin Builder initialization...");
				be.printStackTrace();
			}
		}
	}
	
	public String getPlugin() {
		return this.result;
	}
}
