package com.td.boss.util;

/**
 * @author:slambb
 * @date:2021/12/30
 */

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * 运行脚本
 *
 * @author Ruby
 */
public class RunScript {

    private ScriptEngineManager manager = new ScriptEngineManager();
    private ScriptEngine engine;
    private String fileName;
    private String dAppName = "D:\\CocosProject\\2.1.4\\FragrantTown_Server\\src\\main\\resources\\static\\dapp\\dapp-plugin.min.js";

    public RunScript(String fileName) {
        engine = manager.getEngineByName("JavaScript");
        this.fileName = fileName;
    }

    /**
     * 设置变量
     *
     * @param varName
     * @param obj
     */
    public void setVar(String varName, Object obj) {
        engine.put(varName, obj);
    }

    /**
     * 启动脚本
     *
     * @throws FileNotFoundException
     * @throws ScriptException
     */
    public void start() throws FileNotFoundException, ScriptException, NoSuchMethodException {
        //engine.eval(new FileReader(dAppName));
        engine.eval(new FileReader(fileName));
    }
    public void invoke(String name,Object... args) throws ScriptException, NoSuchMethodException {
        Invocable inv = (Invocable) engine;
        inv.invokeFunction(name, args);
    }


}