package ru.dbotthepony.kstarbound.network.packets.clientbound

import ru.dbotthepony.kommons.io.writeStruct2d
import ru.dbotthepony.kstarbound.client.ClientConnection
import ru.dbotthepony.kstarbound.io.readVector2d
import ru.dbotthepony.kstarbound.math.vector.Vector2d
import ru.dbotthepony.kstarbound.network.IClientPacket
import java.io.DataInputStream
import java.io.DataOutputStream

class UpdateDungeonGravityPacket(val id: Int, val gravity: Vector2d?) : IClientPacket {
	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeShort(id)

		if (gravity == null) {
			stream.writeBoolean(false)
		} else {
			stream.writeBoolean(true)

			if (isLegacy) {
				stream.writeFloat(gravity.y.toFloat())
			} else {
				stream.writeStruct2d(gravity)
			}
		}
	}

	override fun play(connection: ClientConnection) {
		connection.enqueue {
			world?.setDungeonGravity(this@UpdateDungeonGravityPacket.id, gravity)
		}
	}

	companion object {
		fun read(stream: DataInputStream, isLegacy: Boolean): UpdateDungeonGravityPacket {
			val id = stream.readUnsignedShort()
			val gravity: Vector2d?

			if (stream.readBoolean()) {
				if (isLegacy) {
					gravity = Vector2d(y = stream.readFloat().toDouble())
				} else {
					gravity = stream.readVector2d()
				}
			} else {
				gravity = null
			}

			return UpdateDungeonGravityPacket(id, gravity)
		}
	}
}
