// generated by FBuilder
package flexa.ff;
import flexa.fb.*;
import java.util.Map;
import java.util.HashMap;
import javax.script.*;
import java.util.ArrayList;
public class fmethod extends FComponent {
    //
    // CONSTRUCTOR
    //
    public fmethod() {
        super("ff.fmethod");
    }
    
    // 
    // Methods
    //
    
    
    public void prepareContext(FContext acontext)  throws Exception { 
    		Log.info("Registering fmethod " + this.name + " in context");
		acontext.registerFunction(this.name, this);
		this.bytecode = this.getMainContainer().bytecode;
		super.prepareContext(acontext);

    }
    


    
    public Object call(FContextInterface contexti, String aname, Object... args)  throws Exception { 
    		if( aname.equals(this.name) ) {
		    FContext context = (FContext)contexti;
		    Log.info("Executing fmethod " + aname);
		    context.log("Executing fmethod " + aname);
		 
		    FContext lcontext = new FContext();
		    context.pushLocalContext(lcontext);
		    
		    // Set args in context
		    if( this.getValue("parameters") != null ) {
		        String[] parts = this.getValue("parameters").toString().split(",");
		        for(int i = 0; i < args.length; i++) {
		            //Log.info("  arg " + i + " = " + args[i] + " name " + parts[i]);
		            if( i > parts.length - 1 ) break;
		            lcontext.setGlobal(parts[i].trim(), args[i]);
		            
		        }
		    }
		    
		    // Find method's bytecode   
		    if( this.getMainContainer().bytecode == null )
		        throw new Exception("No bytecode loaded in " + this.getMainContainer().getCompleteName());
		    Map<String,FBytecode> tbytecodes = this.getMainContainer().bytecode.oscripts.get(this.id);
		    if( tbytecodes == null )
		        throw new Exception("No bytecode found for " + this.id + " in " + this.getMainContainer().getCompleteName());
			FBytecode bcode = tbytecodes.get("code");
		    // Execute bytecode			
			Object tout = null;
			//Log.info("Executing byte code: " + bcode.toString());
		    tout = EFI.runBytecode(bcode, context, false);						 
		    //Log.info("    result: " + tout);
		    // Get returned value
		    //Object tval = context.stack.size() > 0 ? context.stack.pop() : null;
		    context.log("Executed method " + aname);
		    context.log("  returning", tout);
		    Log.info("Executed method " + aname);
		    Log.info("  returning:");
		    Log.info(tout);
		    
		    context.popLocalContext();
		    
		    return tout;
		}
		return null;

    }
    


    // 
    // Events
    //
	public void event(String aAction, FContext aContext) throws Exception {
        // Events
        
	    super.event(aAction, aContext);
	}
	
	
}