package ru.dbotthepony.kstarbound.lua.userdata

import org.classdump.luna.Table
import org.classdump.luna.Userdata
import org.classdump.luna.impl.ImmutableTable
import ru.dbotthepony.kstarbound.lua.luaFunction
import ru.dbotthepony.kstarbound.util.random.AbstractPerlinNoise

class LuaPerlinNoise(val noise: AbstractPerlinNoise) : Userdata<AbstractPerlinNoise>() {
	private var metatable: Table? = Companion.metatable

	override fun getMetatable(): Table? {
		return metatable
	}

	override fun setMetatable(mt: Table?): Table? {
		val old = metatable
		metatable = mt
		return old
	}

	override fun getUserValue(): AbstractPerlinNoise {
		return noise
	}

	override fun setUserValue(value: AbstractPerlinNoise?): AbstractPerlinNoise {
		throw UnsupportedOperationException()
	}

	companion object {
		private val metatable = ImmutableTable.Builder()
			.add("get", luaFunction { self: LuaPerlinNoise, x: Number, y: Number?, z: Number? ->
				if (y != null && z != null) {
					returnBuffer.setTo(self.noise[x.toDouble(), y.toDouble(), z.toDouble()])
				} else if (y != null) {
					returnBuffer.setTo(self.noise[x.toDouble(), y.toDouble()])
				} else {
					returnBuffer.setTo(self.noise[x.toDouble()])
				}
			})
			.build()
	}
}
