package ru.dbotthepony.kstarbound.lua.bindings

import ru.dbotthepony.kommons.vector.Vector2d
import ru.dbotthepony.kstarbound.lua.LuaEnvironment
import ru.dbotthepony.kstarbound.lua.from
import ru.dbotthepony.kstarbound.lua.get
import ru.dbotthepony.kstarbound.lua.luaFunction
import ru.dbotthepony.kstarbound.lua.set
import ru.dbotthepony.kstarbound.world.entities.AbstractEntity

fun provideEntityBindings(self: AbstractEntity, lua: LuaEnvironment) {
	val table = lua.newTable()
	lua.globals["entity"] = table

	table["id"] = luaFunction { returnBuffer.setTo(self.entityID) }
	table["position"] = luaFunction { returnBuffer.setTo(from(self.position)) }
	table["entityType"] = luaFunction { returnBuffer.setTo(self.type.jsonName) }
	table["uniqueId"] = luaFunction { returnBuffer.setTo(self.uniqueID.get().orNull()) }
	table["persistent"] = luaFunction { returnBuffer.setTo(self.isPersistent) }

	table["entityInSight"] = luaFunction { TODO() }
	table["isValidTarget"] = luaFunction { TODO() }

	table["damageTeam"] = luaFunction {
		val result = newTable()

		result["team"] = self.team.get().team
		result["type"] = self.type.jsonName

		returnBuffer.setTo(result)
	}

	table["distanceToEntity"] = luaFunction { entity: Number ->
		val find = self.world.entities[entity.toInt()]

		if (find != null) {
			returnBuffer.setTo(from(self.world.geometry.diff(find.position, self.position)))
		} else {
			returnBuffer.setTo(from(Vector2d.ZERO))
		}
	}
}
