package lc.esp.script.engine;

import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import org.junit.jupiter.api.Test;

import javax.script.ScriptException;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class ScriptContextTest {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ScriptContextTest.class);

    @Test
    public void testEngine() throws ScriptException, TimeoutException, ExecutionException, InterruptedException, IOException {
        ESPScriptEngine sc = new ESPScriptEngine();
        sc.getEngine().eval("var x = 2+2");
        // new context
        sc.eval("var x = 2+2; var y = 1+1;");
        assertEquals(4, sc.get("x"));
        assertEquals(null, sc.get("y"));
    }

    @Test
    public void scriptInterruptionTest() throws ScriptException, ExecutionException, InterruptedException, IOException {
        ESPScriptEngine sc = new ESPScriptEngine();
        sc.setTimeoutMs(1);
        boolean worked = false;
        try {
            sc.eval("while(true){}");
        } catch (TimeoutException e) {
            worked = true;
        }

        assert (worked);
    }

    @Test
    public void checkJavaAccessTest() throws TimeoutException, InterruptedException, IOException {
        ESPScriptEngine sc = new ESPScriptEngine();
        boolean worked = false;
        try {
            sc.eval("System.exit(0);");
        } catch (ExecutionException e) {
            worked = true;
        }
        assert (worked);
    }

    @Test
    public void importTest() throws ExecutionException, InterruptedException, TimeoutException, IOException {
        ESPScriptEngine sc = new ESPScriptEngine();
        sc.eval("import {x} from 'lib'");
    }
}
