package org.luaj.vm2.libs.jse;

import org.luaj.vm2.LuaValue;
import org.luaj.vm2.libs.ApproxLib;

/**
 * Host-side helpers for mirroring Java state into Lua without reacting to
 * insignificant floating-point drift.
 */
public final class LuaStateSync {

	private LuaStateSync() {
	}

	public static boolean setIfApproxChanged(LuaValue target, LuaValue key, double value, double epsilon) {
		if (epsilon < 0d) {
			throw new IllegalArgumentException("epsilon must be >= 0");
		}
		LuaValue current = target.get(key);
		if (current.isnumber() && ApproxLib.approxEqual(current.todouble(), value, epsilon)) {
			return false;
		}
		target.set(key, LuaValue.valueOf(value));
		return true;
	}

	public static boolean setIfApproxChanged(LuaValue target, String key, double value, double epsilon) {
		return setIfApproxChanged(target, LuaValue.valueOf(key), value, epsilon);
	}

	public static boolean setIfApproxChanged(LuaValue target, int key, double value, double epsilon) {
		return setIfApproxChanged(target, LuaValue.valueOf(key), value, epsilon);
	}

	public static boolean approxEqual(double a, double b, double epsilon) {
		if (epsilon < 0d) {
			throw new IllegalArgumentException("epsilon must be >= 0");
		}
		return ApproxLib.approxEqual(a, b, epsilon);
	}
}
