package flexa.ff;

import flexa.fb.*;
import java.util.Map;
import java.util.HashMap;


public class fmethod extends FComponent {
    
    public fmethod() {
        super("ff.fmethod");
    }

	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);
		 
		    // Set args in context
		    String[] parts = this.getValue("parameters").toString().split(",");
		    for(int i = 0; i < args.length; i++) {
		        //Log.info("  arg " + i + " = " + args[i] + " name " + parts[i]);
		        context.setGlobal(parts[i].trim(), args[i]);
		    }
		    // Find method's bytecode
            Map<String,FBytecode> tbytecodes = this.bytecode.oscripts.get(this.id);
			FBytecode bcode = tbytecodes.get("code");

            // Execute bytecode			
			Object tout = null;
			//Log.info("Executing byte code: " + bcode.toString());
		    tout = EFI.runBytecode(bcode, context);						 
		    //Log.info("    result: " + tout);

		    // Get returned value
		    Object tval = context.stack.pop();
		    return tval;
		}
		return null;
    }
	
    
}