package ru.dbotthepony.kstarbound.lua

import ru.dbotthepony.kstarbound.Starbound

class LuaUpdateComponent(val lua: LuaEnvironment) {
	var stepCount = 1.0
	private var steps = 0.0

	init {
		val script = lua.newTable()
		lua.globals["script"] = script

		script["updateDt"] = luaFunction {
			returnBuffer.setTo(stepCount * Starbound.TIMESTEP)
		}

		script["setUpdateDelta"] = luaFunction { ticks: Number ->
			stepCount = ticks.toDouble()
		}
	}

	fun update(delta: Double, vararg arguments: Any?) {
		if (stepCount == 0.0)
			return

		steps += delta / Starbound.TIMESTEP

		if (steps >= stepCount) {
			steps %= stepCount
			lua.invokeGlobal("update", stepCount * Starbound.TIMESTEP, *arguments)
		}
	}
}
