package dev.exhq.ajarc.vm;

import delight.nashornsandbox.NashornSandbox;
import delight.nashornsandbox.NashornSandboxes;
import delight.nashornsandbox.internal.JsSanitizer;
import dev.exhq.ajarc.Ajar;
import dev.exhq.ajarc.computer.ComputerBlockEntity;
import dev.exhq.ajarc.computer.ComputerTerminal;
import net.minecraft.client.Minecraft;
import org.apache.commons.io.IOUtils;

import javax.script.ScriptException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class JsVm {
	private final NashornSandbox sandbox;

	public JsVm(ComputerBlockEntity entity) {
		sandbox = NashornSandboxes.create();
		sandbox.inject("screen", new ScreenHelper(entity));
	}

	public record ScreenHelper(ComputerBlockEntity entity) {
		public void setScreenSize(int rows, int cols) {
			entity.setTerminal(ComputerTerminal.ofSize(rows, cols));
		}
	}

	public int add(int left, int right) {
		String text;
		try {
			var stream = Minecraft.getInstance()
			                      .getResourceManager()
			                      .getResourceOrThrow(Ajar.identifier("script.js"))
			                      .open();
			text = IOUtils.toString(stream, StandardCharsets.UTF_8);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		var bindings = sandbox.createBindings();
		bindings.put("left", left);
		bindings.put("right", right);
		try {
			sandbox.eval(text, bindings);
		} catch (ScriptException e) {
			throw new RuntimeException(e);
		}

		return (int) (double) bindings.get("result");
	}
}