package cn.fateverse.query;

import cn.fateverse.common.code.engine.JavaScriptEngine;
import cn.fateverse.common.code.model.EngineResult;
import com.alibaba.fastjson2.JSONObject;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;
import org.junit.jupiter.api.Test;

import javax.script.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

/**
 * @author Clay
 * @date 2024/4/23 9:42
 */
public class JavaScriptParamTest {


    static String finalCode = "function execute1(data) {\n" +
            "    let  res = [data.length];\n" +
            "    for (let i = 0; i < data.length; i++) {\n" +
            "        console.log(data[i])\n" +
            "        console.log(data[i].foo)\n" +
            "        res[i] = data[i].foo\n" +
            "    }\n" +
            "    return res;\n" +
            "}";

    @Test
    public void testParam() {
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {

            Map<String, Object> param = new HashMap<>();
            param.put("foo", "sdsdsdsds");
            list.add(param);
        }

        ScriptEngineManager engineManager = new ScriptEngineManager();
        ScriptEngine jsEngine = engineManager.getEngineByName("graal.js");
        Context context = Context.newBuilder()
                .allowAllAccess(true)
                .build();
//        Context context = Context.create();
        context.eval("js", finalCode);

        Value executeFunction = context.getBindings("js").getMember("execute1");
        Value javaObjectAsValue = Value.asValue(list);
        Value result = executeFunction.execute(javaObjectAsValue);
        System.out.println(result);

    }


    @Test
    public void testParam2() throws Exception {

        ScriptEngineManager engineManager = new ScriptEngineManager();
        ScriptEngine jsEngine = engineManager.getEngineByName("graal.js");
        Invocable funcCall = (Invocable) jsEngine;
        Bindings bindings = jsEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.put("polyglot.js.allowHostAccess", true);
        bindings.put("polyglot.js.allowHostClassLookup", (Predicate<String>) s -> true);

        jsEngine.eval(finalCode);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("foo", "sdsdsdsds");
        Object res= funcCall.invokeFunction("execute1", jsonObject);

    }

}
