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

import ru.dbotthepony.kommons.io.readCollection
import ru.dbotthepony.kommons.io.readVector2d
import ru.dbotthepony.kommons.io.readVector2f
import ru.dbotthepony.kommons.io.readVector2i
import ru.dbotthepony.kommons.io.writeCollection
import ru.dbotthepony.kommons.io.writeStruct2d
import ru.dbotthepony.kommons.io.writeStruct2f
import ru.dbotthepony.kommons.io.writeStruct2i
import ru.dbotthepony.kommons.vector.Vector2d
import ru.dbotthepony.kommons.vector.Vector2i
import ru.dbotthepony.kstarbound.defs.tile.TileDamage
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import java.io.DataInputStream
import java.io.DataOutputStream

class DamageTileGroupPacket(val tiles: Collection<Vector2i>, val isBackground: Boolean, val sourcePosition: Vector2d, val damage: TileDamage, val source: Int?) : IServerPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(
		stream.readCollection { readVector2i() },
		stream.readBoolean(),
		if (isLegacy) stream.readVector2f().toDoubleVector() else stream.readVector2d(),
		TileDamage(stream, isLegacy),
		if (stream.readBoolean()) stream.readInt() else null
	)

	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeCollection(tiles) { writeStruct2i(it) }
		stream.writeBoolean(isBackground)

		if (isLegacy)
			stream.writeStruct2f(sourcePosition.toFloatVector())
		else
			stream.writeStruct2d(sourcePosition)

		damage.write(stream, isLegacy)
		stream.writeBoolean(source != null)

		if (source != null)
			stream.writeInt(source)
	}

	override fun play(connection: ServerConnection) {
		connection.enqueue {
			damageTiles(tiles, isBackground, sourcePosition, damage)
		}
	}
}
