package ru.dbotthepony.kstarbound.network.packets

import org.apache.logging.log4j.LogManager
import ru.dbotthepony.kstarbound.Starbound
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import java.io.DataInputStream
import java.io.DataOutputStream

data class ProtocolRequestPacket(val version: Int) : IServerPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(stream.readInt())

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

	override fun play(connection: ServerConnection) {
		if (version == Starbound.NATIVE_PROTOCOL_VERSION) {
			connection.channel.write(ProtocolResponsePacket(true))
			connection.channel.flush()
			connection.setupNative()
		} else if (version == Starbound.LEGACY_PROTOCOL_VERSION) {
			connection.channel.write(ProtocolResponsePacket(true))
			connection.channel.flush()
			connection.setupLegacy()
		} else {
			LOGGER.info("Unsupported protocol version on $connection, closing.")
			connection.channel.write(ProtocolResponsePacket(false))
			connection.channel.flush()
			connection.close()
		}
	}

	companion object {
		private val LOGGER = LogManager.getLogger()
	}
}
