package ru.dbotthepony.kstarbound.network.packets.clientbound

import ru.dbotthepony.kommons.io.writeBinaryString
import ru.dbotthepony.kstarbound.client.ClientConnection
import ru.dbotthepony.kstarbound.io.readInternedString
import ru.dbotthepony.kstarbound.io.readVector2d
import ru.dbotthepony.kstarbound.io.writeStruct2d
import ru.dbotthepony.kstarbound.math.vector.Vector2d
import ru.dbotthepony.kstarbound.network.IClientPacket
import java.io.DataInputStream
import java.io.DataOutputStream

class FindUniqueEntityResponsePacket(val name: String, val position: Vector2d?) : IClientPacket {
	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeBinaryString(name)
		stream.writeBoolean(position != null)

		if (position != null)
			stream.writeStruct2d(position, isLegacy)
	}

	override fun play(connection: ClientConnection) {
		connection.enqueue {
			world?.pendingUniqueEntityRequests?.asMap()?.remove(name)?.complete(position)
		}
	}

	companion object {
		fun read(stream: DataInputStream, isLegacy: Boolean): FindUniqueEntityResponsePacket {
			val name = stream.readInternedString()
			val position: Vector2d?

			if (stream.readBoolean()) {
				position = stream.readVector2d(isLegacy)
			} else {
				position = null
			}

			return FindUniqueEntityResponsePacket(name, position)
		}
	}
}