package ru.dbotthepony.kstarbound.network.packets.serverbound

import ru.dbotthepony.kommons.io.readSignedVarInt
import ru.dbotthepony.kommons.io.writeSignedVarInt
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.network.packets.clientbound.GiveItemPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import ru.dbotthepony.kstarbound.world.entities.ItemDropEntity
import java.io.DataInputStream
import java.io.DataOutputStream

class RequestDropPacket(val id: Int) : IServerPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(stream.readSignedVarInt())

	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeSignedVarInt(id)
	}

	override fun play(connection: ServerConnection) {
		connection.enqueue {
			val item = entities[id] as? ItemDropEntity ?: return@enqueue
			val player = connection.playerEntity ?: return@enqueue

			if (item.canTake) {
				val take = item.take(player)

				if (take.isNotEmpty) {
					connection.send(GiveItemPacket(take.createDescriptor()))
				}
			}
		}
	}
}
