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

import ru.dbotthepony.kommons.io.readSignedVarInt
import ru.dbotthepony.kommons.io.writeSignedVarInt
import ru.dbotthepony.kstarbound.math.vector.Vector2i
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import ru.dbotthepony.kstarbound.world.entities.tile.WireNode
import ru.dbotthepony.kstarbound.world.entities.tile.WorldObject
import java.io.DataInputStream
import java.io.DataOutputStream

class DisconnectAllWiresPacket(val pos: Vector2i, val node: WireNode) : IServerPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(Vector2i(stream.readSignedVarInt(), stream.readSignedVarInt()), WireNode(stream, isLegacy))

	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeSignedVarInt(pos.x)
		stream.writeSignedVarInt(pos.y)
		node.write(stream, isLegacy)
	}

	override fun play(connection: ServerConnection) {
		connection.enqueue {
			val target = entityIndex.tileEntityAt(pos) as? WorldObject ?: return@enqueue
			val node = if (node.isInput) target.inputNodes.getOrNull(node.index) else target.outputNodes.getOrNull(node.index)
			node?.removeAllConnections()
		}
	}
}
