// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package m2m;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;

public class TestScript {
    public static class Data {
        public int iv;
        public String sv;
        public Data(int iv, String sv) {
            this.iv = iv;
            this.sv = sv;
        }
        public void m() {
            iv++;
            sv += "X";
        }
        @Override
        public String toString() {
            return String.format("(%d,%s)", iv, sv);
        }
    }
    public static void test(String language, String source) throws ScriptException {
        System.out.println(language);
        System.out.println(source);
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine se = sem.getEngineByName(language);
        ScriptContext ctx = new SimpleScriptContext();
        ctx.setAttribute("n", 3, ScriptContext.ENGINE_SCOPE);
        ctx.setAttribute("s", "Hi", ScriptContext.ENGINE_SCOPE);
        ctx.setAttribute("o", new Data(123, "ABC"), ScriptContext.ENGINE_SCOPE);
        se.eval(source, ctx);
        Data o = (Data)ctx.getAttribute("o");
        System.out.println(o);
    }
    public static void main(String[] args) throws ScriptException {
        test("javascript", "for(i = 0; i < n; i++) {\r\n" +
                            "    print(\"JavaScript says: \" + s)\r\n" +
                            "}\r\n" +
                            "o.iv = o.iv + 1;\r\n" +
                            "o.sv = o.sv + \"X\";\r\n" +
                            "o.m();");
        test("python", "for i in range(n):\r\n" +
                       "    print('Python says: ' + s)\r\n" +
                       "o.iv = o.iv + 1\r\n" +
                       "o.sv = o.sv + 'X'\r\n" +
                       "o.m()");
        test("jruby", "for i in 1..n do\r\n" +
                      "    puts 'Ruby says: ' + s\r\n" +
                      "end\r\n" +
                      "o.iv = o.iv + 1\r\n" +
                      "o.sv = o.sv + 'X'\r\n" +
                      "o.m()");
        test("php", "<?php\r\n" +
                    "for($i = 0; $i < $n; $i++) {\r\n" +
                    "    echo 'PHP says: ' . $s . \"\\r\\n\";\r\n" +
                    "}\r\n" +
                    "$o->iv = $o->iv + 1;\r\n" +
                    "$o->sv = $o->sv . 'X';\r\n" +
                    "$o->m();\r\n" +
                    "?>");
        test("groovy", "for(i = 0; i < n; i++) {\r\n" +
             "    println \"Groovy says: \" + s\r\n" +
             "}\r\n" +
             "o.iv = o.iv + 1\r\n" +
             "o.sv = o.sv + \"X\"\r\n" +
             "o.m()");
    }
}
