package com.gyee.alarm.rule;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilerConfiguration;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ScriptShell {
    private static final GroovyShell shell;
    private static ConcurrentHashMap<String, Script> cache = new ConcurrentHashMap<String, Script>();

    static {
        CompilerConfiguration cfg = new CompilerConfiguration();
        cfg.setScriptBaseClass(AlarmScript.class.getName());
        shell = new GroovyShell(cfg);
    }

    public static Object parseExpr(String expr) {
        Script s = getScriptFromCache(expr);
        return s.run();
    }

    public static Object parseExpr(String expr, Map<String, Object> map) {
        Binding binding = new Binding(map);
        Script script = getScriptFromCache(expr);
        script.setBinding(binding);
        return script.run();
    }

    private static Script getScriptFromCache(String expr) {
        if (cache.containsKey(expr)) {
            return cache.get(expr);
        }
        Script script = shell.parse(expr);
        cache.put(expr, script);
        return script;
    }


}