PhysicalConnectivity/src/main/kotlin/net/shadowfacts/phycon/network/block/networkinterface/NetworkInterfaceBlockEntity.kt

52 lines
1.6 KiB
Kotlin

package net.shadowfacts.phycon.network.block.networkinterface
import alexiil.mc.lib.attributes.SearchOptions
import alexiil.mc.lib.attributes.item.GroupedItemInv
import alexiil.mc.lib.attributes.item.ItemAttributes
import net.minecraft.item.ItemStack
import net.minecraft.util.math.Direction
import net.shadowfacts.phycon.api.packet.Packet
import net.shadowfacts.phycon.init.PhyBlockEntities
import net.shadowfacts.phycon.network.DeviceBlockEntity
import net.shadowfacts.phycon.network.packet.ReadAllPacket
import net.shadowfacts.phycon.network.packet.RequestReadAllPacket
/**
* @author shadowfacts
*/
class NetworkInterfaceBlockEntity: DeviceBlockEntity(PhyBlockEntities.NETWORK_INTERFACE) {
private val facing: Direction
get() = world!!.getBlockState(pos)[NetworkInterfaceBlock.FACING]
// todo: should this be a weak ref?
private var inventory: GroupedItemInv? = null
fun updateInventory() {
val offsetPos = pos.offset(facing)
val option = SearchOptions.inDirection(facing)
inventory = ItemAttributes.GROUPED_INV.getFirstOrNull(world, offsetPos, option)
}
override fun handlePacket(packet: Packet) {
when (packet) {
is RequestReadAllPacket -> handleReadAll(packet)
}
}
fun handleReadAll(packet: RequestReadAllPacket) {
enqueueToSingle(ReadAllPacket(readAll(), macAddress, packet.source))
}
fun readAll(): Map<ItemStack, Int> {
// if we don't have an inventory, try to get one
// this happens when readAll is called before a neighbor state changes, such as immediately after world load
if (inventory == null) updateInventory()
return inventory?.let {
it.storedStacks.associateWith(it::getAmount)
} ?: mapOf()
}
}