package ru.dbotthepony.kstarbound.json.factory

import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSet
import com.google.gson.JsonSyntaxException
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

class ImmutableSetTypeAdapter<E>(val elementAdapter: TypeAdapter<E>) : TypeAdapter<ImmutableSet<E>>() {
	override fun write(out: JsonWriter, value: ImmutableSet<E>?) {
		if (value == null) {
			out.nullValue()
			return
		}

		out.beginArray()

		for (v in value) {
			elementAdapter.write(out, v)
		}

		out.endArray()
	}

	override fun read(reader: JsonReader): ImmutableSet<E>? {
		if (reader.consumeNull())
			return null

		reader.beginArray()

		val builder = ImmutableSet.Builder<E>()

		while (reader.peek() != JsonToken.END_ARRAY) {
			val readObject = elementAdapter.read(reader) ?: throw JsonSyntaxException("List does not accept nulls")
			builder.add(readObject)
		}

		reader.endArray()

		return builder.build()
	}
}
