package ru.dbotthepony.kstarbound.defs

import com.google.gson.JsonElement
import com.google.gson.JsonNull
import ru.dbotthepony.kstarbound.json.builder.IStringSerializable
import ru.dbotthepony.kstarbound.json.readJsonElement
import ru.dbotthepony.kstarbound.json.writeJsonElement
import java.io.DataInputStream
import java.io.DataOutputStream

data class InteractAction(val type: Type = Type.NONE, val entityID: Int = 0, val data: JsonElement = JsonNull.INSTANCE) {
	// int32_t
	enum class Type(override val jsonName: String) : IStringSerializable {
		NONE("None"),
		OPEN_CONTAINER("OpenContainer"),
		SIT_DOWN("SitDown"),
		OPEN_CRAFTING_INTERFACE("OpenCraftingInterface"),
		OPEN_SONGBOOK_INTERFACE("OpenSongbookInterface"),
		OPEN_NPC_CRAFTING_INTERFACE("OpenNpcCraftingInterface"),
		OPEN_MERCHANT_INTERFACE("OpenMerchantInterface"),
		OPEN_AI_INTERFACE("OpenAiInterface"),
		OPEN_TELEPORT_DIALOG("OpenTeleportDialog"),
		SHOW_POPUP("ShowPopup"),
		SCRIPT_PANE("ScriptPane"),
		MESSAGE("Message");
	}

	constructor(type: String, entityID: Int = 0, data: JsonElement = JsonNull.INSTANCE) : this(
		Type.entries.firstOrNull { it.jsonName == type } ?: throw NoSuchElementException("No such interaction action $type!"), entityID, data
	)

	constructor(stream: DataInputStream, isLegacy: Boolean) : this(
		if (isLegacy) Type.entries[stream.readInt()] else Type.entries[stream.readUnsignedByte()],
		stream.readInt(),
		stream.readJsonElement()
	)

	fun write(stream: DataOutputStream, isLegacy: Boolean) {
		if (isLegacy) stream.writeInt(type.ordinal) else stream.writeByte(type.ordinal)
		stream.writeInt(entityID)
		stream.writeJsonElement(data)
	}

	companion object {
		val NONE = InteractAction()
	}
}
