package ru.dbotthepony.kstarbound.network.packets

import it.unimi.dsi.fastutil.bytes.ByteArrayList
import org.apache.logging.log4j.LogManager
import ru.dbotthepony.kommons.io.readByteArray
import ru.dbotthepony.kommons.io.readSignedVarInt
import ru.dbotthepony.kommons.io.writeByteArray
import ru.dbotthepony.kommons.io.writeSignedVarInt
import ru.dbotthepony.kstarbound.client.ClientConnection
import ru.dbotthepony.kstarbound.network.IClientPacket
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import ru.dbotthepony.kstarbound.world.entities.AbstractEntity
import java.io.DataInputStream
import java.io.DataOutputStream

class EntityDestroyPacket(val entityID: Int, val finalNetState: ByteArrayList, val isDeath: Boolean) : IClientPacket, IServerPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(stream.readSignedVarInt(), ByteArrayList.wrap(stream.readByteArray()), stream.readBoolean())

	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeSignedVarInt(entityID)
		stream.writeByteArray(finalNetState.elements(), 0, finalNetState.size)
		stream.writeBoolean(isDeath)
	}

	override fun play(connection: ServerConnection) {
		if (entityID !in connection.entityIDRange) {
			LOGGER.error("Client $connection tried to remove entity with ID $entityID, but that's outside of allowed range ${connection.entityIDRange}!")
			connection.disconnect("Removing entity with ID $entityID outside of allowed range ${connection.entityIDRange}")
		} else {
			connection.enqueue {
				entities[entityID]?.remove(if (isDeath) AbstractEntity.RemovalReason.REMOTE_DYING else AbstractEntity.RemovalReason.REMOTE_REMOVAL)
			}
		}
	}

	override fun play(connection: ClientConnection) {
		TODO("Not yet implemented")
	}

	companion object {
		private val LOGGER = LogManager.getLogger()
	}
}