package ru.dbotthepony.kstarbound.json

import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.stream.JsonWriter
import ru.dbotthepony.kommons.io.readBinaryString
import ru.dbotthepony.kstarbound.Starbound
import ru.dbotthepony.kstarbound.json.builder.JsonFactory
import java.io.DataInputStream

@JsonFactory
data class VersionedJson(val identifier: String, val version: Int?, val content: JsonElement) {
	constructor(data: DataInputStream) : this(
		data.readBinaryString(),
		data.read().let { if (it > 0) data.readInt() else null },
		data.readJsonElement())

	fun toJson(): JsonObject {
		return adapter.toJsonTree(this) as JsonObject
	}

	fun toJson(writer: JsonWriter) {
		adapter.write(writer, this)
	}

	companion object {
		private val adapter by lazy { Starbound.gson.getAdapter<VersionedJson>() }
	}
}
