package ru.dbotthepony.kstarbound.defs

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.annotations.JsonAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import ru.dbotthepony.kommons.io.writeBinaryString
import ru.dbotthepony.kstarbound.io.readInternedString
import ru.dbotthepony.kstarbound.io.readNullableDouble
import ru.dbotthepony.kstarbound.io.writeNullable
import ru.dbotthepony.kstarbound.io.writeNullableDouble
import ru.dbotthepony.kstarbound.json.builder.FactoryAdapter
import java.io.DataInputStream
import java.io.DataOutputStream

@JsonAdapter(EphemeralStatusEffect.Adapter::class)
data class EphemeralStatusEffect(val effect: String, val duration: Double? = null) {
	constructor(stream: DataInputStream, isLegacy: Boolean) : this(stream.readInternedString(), stream.readNullableDouble())

	class Adapter(gson: Gson) : TypeAdapter<EphemeralStatusEffect>() {
		private val factory = FactoryAdapter.createFor(EphemeralStatusEffect::class, gson = gson)

		override fun write(out: JsonWriter, value: EphemeralStatusEffect) {
			if (value.duration == null)
				out.value(value.effect)
			else
				factory.write(out, value)
		}

		override fun read(`in`: JsonReader): EphemeralStatusEffect {
			if (`in`.peek() == JsonToken.STRING)
				return EphemeralStatusEffect(`in`.nextString())
			else
				return factory.read(`in`)
		}
	}

	fun write(stream: DataOutputStream, isLegacy: Boolean) {
		stream.writeBinaryString(effect)
		stream.writeNullableDouble(duration, isLegacy)
	}
}
