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

import it.unimi.dsi.fastutil.bytes.ByteArrayList
import it.unimi.dsi.fastutil.io.FastByteArrayInputStream
import ru.dbotthepony.kommons.io.readByteArray
import ru.dbotthepony.kommons.io.writeByteArray
import ru.dbotthepony.kstarbound.defs.EntityType
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import ru.dbotthepony.kstarbound.world.entities.ItemDropEntity
import java.io.DataInputStream
import java.io.DataOutputStream

// similar to EntityCreatePacket, except client transfers ownership of entity to server
class SpawnEntityPacket(val entityType: EntityType, val storeData: ByteArrayList, val firstNetState: ByteArrayList,) : IServerPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(
		EntityType.entries[stream.readUnsignedByte()],
		ByteArrayList.wrap(stream.readByteArray()),
		ByteArrayList.wrap(stream.readByteArray()),
	)

	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeByte(entityType.ordinal)
		stream.writeByteArray(storeData.elements(), 0, storeData.size)
		stream.writeByteArray(firstNetState.elements(), 0, firstNetState.size)
	}

	override fun play(connection: ServerConnection) {
		val entity = when (entityType) {
			EntityType.ITEM_DROP -> ItemDropEntity(DataInputStream(FastByteArrayInputStream(storeData.elements(), 0, storeData.size)), connection.isLegacy)
			else -> null
		}

		entity ?: return
		entity.networkGroup.read(firstNetState, isLegacy = connection.isLegacy)

		connection.enqueue {
			entity.joinWorld(this)
		}
	}
}