package ru.dbotthepony.kstarbound.network.packets

import ru.dbotthepony.kstarbound.client.ClientConnection
import ru.dbotthepony.kstarbound.defs.DamageNotification
import ru.dbotthepony.kstarbound.network.IClientPacket
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import ru.dbotthepony.kstarbound.server.world.ServerWorldTracker
import java.io.DataInputStream
import java.io.DataOutputStream

// Why does this specify source, when DamageNotification already contains it?????????????
class DamageNotificationPacket(val source: Int, val notification: DamageNotification) : IServerPacket, IClientPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(stream.readInt(), DamageNotification(stream, isLegacy))

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

	fun shouldNetworkTo(client: ServerWorldTracker): Boolean {
		return source in client.client.entityIDRange ||
			notification.targetEntityId in client.client.entityIDRange ||
			client.isTracking(source) ||
			client.isTracking(notification.position)
	}

	override fun play(connection: ServerConnection) {
		connection.enqueue {
			pushRemoteDamageNotification(this@DamageNotificationPacket)

			for (client in clients) {
				if (client.client !== connection && shouldNetworkTo(client)) {
					client.send(this@DamageNotificationPacket)
				}
			}
		}
	}

	override fun play(connection: ClientConnection) {
		connection.enqueue {
			world?.pushRemoteDamageNotification(this@DamageNotificationPacket)
		}
	}
}
