package ru.dbotthepony.kstarbound.network.packets

import ru.dbotthepony.kstarbound.client.ClientConnection
import ru.dbotthepony.kstarbound.defs.DamageData
import ru.dbotthepony.kstarbound.network.Connection
import ru.dbotthepony.kstarbound.network.IClientPacket
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import java.io.DataInputStream
import java.io.DataOutputStream

class HitRequestPacket(val inflictor: Int, val target: Int, val request: DamageData) : IServerPacket, IClientPacket {
	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeInt(inflictor)
		stream.writeInt(target)
		request.write(stream, isLegacy)
	}

	val destinationConnection: Int
		get() = Connection.connectionForEntityID(inflictor)

	override fun play(connection: ServerConnection) {
		connection.enqueue {
			pushRemoteHitRequest(this@HitRequestPacket)
		}
	}

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

	companion object {
		fun read(stream: DataInputStream, isLegacy: Boolean): HitRequestPacket {
			val inflictor = stream.readInt()
			val target = stream.readInt()
			val data = DamageData(stream, isLegacy, inflictor)
			return HitRequestPacket(inflictor, target, data)
		}
	}
}