package ru.dbotthepony.kstarbound.json.factory

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import ru.dbotthepony.kommons.gson.consumeNull
import ru.dbotthepony.kommons.math.RGBAColor

// because despite description of "jsonToColor" in StarJsonExtra.hpp, they DO NOT support
// floats, color is always defined with 0-255 int components
object RGBAColorTypeAdapter : TypeAdapter<RGBAColor>() {
	override fun write(out: JsonWriter, value: RGBAColor?) {
		if (value == null)
			out.nullValue()
		else {
			out.beginArray()

			out.value(value.redInt)
			out.value(value.greenInt)
			out.value(value.blueInt)
			out.value(value.alphaInt)

			out.endArray()
		}
	}

	override fun read(`in`: JsonReader): RGBAColor? {
		if (`in`.consumeNull())
			return null

		`in`.beginArray()

		val red = `in`.nextInt()
		val green = `in`.nextInt()
		val blue = `in`.nextInt()
		val alpha = `in`.peek().let { if (it == JsonToken.END_ARRAY) 255 else `in`.nextInt() }

		val result = RGBAColor(red, green, blue, alpha)

		`in`.endArray()
		return result
	}
}