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

import ru.dbotthepony.kommons.io.readUUID
import ru.dbotthepony.kommons.io.writeUUID
import ru.dbotthepony.kstarbound.client.ClientConnection
import ru.dbotthepony.kstarbound.defs.InteractAction
import ru.dbotthepony.kstarbound.defs.InteractRequest
import ru.dbotthepony.kstarbound.network.Connection
import ru.dbotthepony.kstarbound.network.IClientPacket
import ru.dbotthepony.kstarbound.network.IServerPacket
import ru.dbotthepony.kstarbound.network.packets.clientbound.EntityInteractResultPacket
import ru.dbotthepony.kstarbound.server.ServerConnection
import java.io.DataInputStream
import java.io.DataOutputStream
import java.util.UUID

class EntityInteractPacket(val request: InteractRequest, val id: UUID) : IServerPacket, IClientPacket {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(
		InteractRequest(stream, isLegacy),
		stream.readUUID()
	)

	override fun write(stream: DataOutputStream, isLegacy: Boolean) {
		request.write(stream, isLegacy)
		stream.writeUUID(id)
	}

	override fun play(connection: ServerConnection) {
		if (request.target >= 0) {
			connection.enqueue {
				connection.send(EntityInteractResultPacket(entities[request.target]?.interact(request) ?: InteractAction.NONE, id, request.source))
			}
		} else {
			val other = connection.server.channels.connectionByID(Connection.connectionForEntityID(request.target)) ?: throw IllegalArgumentException("No such connection ID ${Connection.connectionForEntityID(request.target)} for EntityInteractPacket")

			if (other == connection) {
				throw IllegalStateException("Attempt to interact with own entity through server?")
			}

			other.send(this)
		}
	}

	override fun play(connection: ClientConnection) {
		TODO("Not yet implemented")
	}
}
