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

import ru.dbotthepony.kommons.io.readCollection
import ru.dbotthepony.kommons.io.readVector2i
import ru.dbotthepony.kommons.io.writeCollection
import ru.dbotthepony.kommons.io.writeStruct2i
import ru.dbotthepony.kommons.vector.Vector2i
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.network.packets.clientbound.TileModificationFailurePacket
import ru.dbotthepony.kstarbound.world.TileModification
import ru.dbotthepony.kstarbound.server.ServerConnection
import java.io.DataInputStream
import java.io.DataOutputStream

class ModifyTileListPacket(val modifications: Collection<Pair<Vector2i, TileModification>>, val allowEntityOverlap: Boolean) : IServerPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(stream.readCollection { stream.readVector2i() to TileModification.read(stream, isLegacy) }, stream.readBoolean())

	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeCollection(modifications) { stream.writeStruct2i(it.first); it.second.write(stream, isLegacy) }
		stream.writeBoolean(allowEntityOverlap)
	}

	override fun play(connection: ServerConnection) {
		val inWorld = connection.enqueue {
			val unapplied = applyTileModifications(modifications, allowEntityOverlap)

			if (unapplied.isNotEmpty()) {
				connection.send(TileModificationFailurePacket(unapplied))
			}
		}

		if (!inWorld) {
			connection.send(TileModificationFailurePacket(modifications))
		}
	}
}
