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.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 Object handle(ContractRequest input, JSEngine engine, Object ret) {
        try {
            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
            ret = ConfidentialContractUtil.executeConfidentialContract(input);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
}
