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

import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import ru.dbotthepony.kstarbound.world.entities.tile.WorldObject
import ru.dbotthepony.kstarbound.world.entities.wire.WireConnection
import java.io.DataInputStream
import java.io.DataOutputStream

class ConnectWirePacket(val target: WireConnection, val source: WireConnection) : IServerPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(WireConnection(stream), WireConnection(stream))

	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		target.write(stream)
		source.write(stream)
	}

	override fun play(connection: ServerConnection) {
		connection.enqueue {
			val target = entityIndex.tileEntityAt(target.entityLocation) as? WorldObject ?: return@enqueue
			val source = entityIndex.tileEntityAt(source.entityLocation) as? WorldObject ?: return@enqueue

			val targetNode = target.outputNodes.getOrNull(this@ConnectWirePacket.target.index) ?: return@enqueue
			val sourceNode = source.inputNodes.getOrNull(this@ConnectWirePacket.source.index) ?: return@enqueue

			targetNode.addConnection(this@ConnectWirePacket.source)
			sourceNode.addConnection(this@ConnectWirePacket.target)
		}
	}
}
