package org.luaj.vm2;

import java.io.StringReader;

import org.luaj.vm2.libs.jme.JmePlatform;

public final class Lua54JmeSmokeTestMain {
	private static void check(String name, Varargs actual, LuaValue... expected) {
		if (actual.narg() != expected.length) {
			throw new IllegalStateException(name + " expected " + expected.length + " values but got " + actual.narg() + ": " + actual);
		}
		for (int i = 0; i < expected.length; i++) {
			LuaValue value = actual.arg(i + 1);
			if (!value.eq_b(expected[i])) {
				throw new IllegalStateException(name + " mismatch at #" + (i + 1) + ": expected " + expected[i] + " but got " + value);
			}
		}
		System.out.println("ok  " + name + " -> " + actual);
	}

	private static Varargs run(String name, String script) throws Exception {
		Globals globals = JmePlatform.debugGlobals();
		return globals.load(new StringReader(script), name).invoke();
	}

	public static void main(String[] args) throws Exception {
		check(
			"bit32_absent_jme",
			run("bit32_absent_jme", "return bit32 == nil\n"),
			LuaValue.TRUE);

		check(
			"randomseed_54_jme",
			run("randomseed_54_jme",
				"local a, b = math.randomseed(13, 17)\n" +
				"local x1, x2 = math.random(), math.random(1, 1000000)\n" +
				"math.randomseed(13, 17)\n" +
				"local y1, y2 = math.random(), math.random(1, 1000000)\n" +
				"return a, b, x1 == y1 and x2 == y2\n"),
			LuaValue.valueOf(13),
			LuaValue.valueOf(17),
			LuaValue.TRUE);

		check(
			"close_scope_jme",
			run("close_scope_jme",
				"local mt = { __close = function(self, err) _G.marker = err or 'closed' end }\n" +
				"do local h <close> = setmetatable({}, mt) end\n" +
				"return marker\n"),
			LuaValue.valueOf("closed"));

		check(
			"io_roundtrip_jme",
			run("io_roundtrip_jme",
				"local path = 'build/lua54-jme-io-smoke.txt'\n" +
				"local out = assert(io.open(path, 'w'))\n" +
				"out:write('smoke')\n" +
				"out:close()\n" +
				"local input = assert(io.open(path, 'r'))\n" +
				"local text = input:read('*a')\n" +
				"input:close()\n" +
				"return text, type(debug)\n"),
			LuaValue.valueOf("smoke"),
			LuaValue.valueOf("table"));
	}
}
