package org.bdware.sc.engine.hook;

import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.engine.ConfidentialContractUtil;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.ArgPacks;
import org.bdware.sc.node.FunctionNode;
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;

public class ConfidentialHandler implements AnnotationHook {
    private final FunctionNode fun;

    public ConfidentialHandler(FunctionNode fun) {
        this.fun = fun;
    }

    @Override
    public ArgPacks handle(JSEngine engine, ArgPacks argPacks) {
        try {
            ContractRequest input = argPacks.request;
            DesktopEngine desktopEngine = (DesktopEngine) engine;
            ConfidentialContractUtil.copyTemplateToDestination(input);
            ScriptObjectMirror globalVars = (ScriptObjectMirror) desktopEngine.get("Global");
            ConfidentialContractUtil.dumpScriptAndStates(
                    desktopEngine.engine, fun, input, globalVars);
            // run in SGX instead of Nashorn if function has @Confidential annotation
            argPacks.ret = ConfidentialContractUtil.executeConfidentialContract(input);
            return argPacks;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return argPacks;
    }
}
