package Templates.API_Support.Execution_API;

import java.io.IOException;

import org.openide.ErrorManager;
import org.openide.execution.ThreadExecutor;
import org.openide.util.HelpCtx;

/** Somehow handles a class present in the Repository by "running" it.
 *
 * @author __USER__
 */
public class __Sample_internal__Executor extends ThreadExecutor {

    // The default value for an unconfigured executor.
    private String myProp = "someDefaultValue";

    public __Sample_internal__Executor() {
    }

    // You may configure this executor as a JavaBean:
    public String getMyProp() {
        return myProp;
    }

    public synchronized void setMyProp(String nue) {
        String old = myProp;
        myProp = nue;
        firePropertyChange("myProp", old, nue);
    }

    protected void checkClass(Class clazz) throws IOException {
        try {
            // Just check that there is nothing seriously wrong with the file,
            // e.g. totally inappropriate type of class, etc.
            // ---WARNING---
            // This code will not work when run from the ExecutorTester, if MyInterface is in
            // the Repository--because MyInterface will be loaded from the same classloader as
            // this executor (i.e. the one created by ExecutorTester to test it), while the class
            // being checked here will be loaded from another repository classloader (i.e. one
            // created by this executor). So the cast will fail. Best to test the executor from
            // inside a test module in this case.
            MyInterface thing = (MyInterface)clazz.newInstance();
        } catch (Exception e) {
            throw mkioe(e);
        } catch (LinkageError e) {
            throw mkioe(e);
        }
    }
    private static IOException mkioe(Throwable t) {
        if (t instanceof IOException) return (IOException)t;
        IOException ioe = new IOException(t);
        ErrorManager.getDefault().annotate(ioe, t);
        return ioe;
    }

    protected void executeClass(Class clazz, String[] args) {
        try {
            // Actually do something with this class, e.g.:
            System.err.println("Starting here -->"); // shown on OutputWindow
            MyInterface thing = (MyInterface)clazz.newInstance();
            // Any calls made in clazz to System.err, etc., will go to OutputWindow automatically:
            thing.doSomething(args, getMyProp());
            System.err.println("<-- and ending.");
        } catch (Exception e) {
            // Will actually go to the OutputWindow automatically:
            e.printStackTrace();
            ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
        } catch (LinkageError e) {
            e.printStackTrace();
            ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
        }
    }

    /*
    public HelpCtx getHelpCtx() {
	return new HelpCtx(__NAME__.class);
    }
    */

}
