package ru.dbotthepony.kstarbound.json.factory

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.TypeAdapterFactory
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import ru.dbotthepony.kommons.gson.consumeNull
import java.lang.reflect.ParameterizedType
import java.util.concurrent.CompletableFuture

object CompletableFutureAdapter : TypeAdapterFactory {
	override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
		if (type.rawType == CompletableFuture::class.java) {
			val type = type.type as? ParameterizedType ?: return null
			val parent = gson.getAdapter(TypeToken.get(type.actualTypeArguments[0])) as TypeAdapter<Any?>

			return object : TypeAdapter<CompletableFuture<Any?>>() {
				override fun write(out: JsonWriter, value: CompletableFuture<Any?>?) {
					parent.write(out, value?.get())
				}

				override fun read(`in`: JsonReader): CompletableFuture<Any?>? {
					return CompletableFuture.completedFuture(parent.read(`in`))
				}
			} as TypeAdapter<T>
		}

		return null
	}
}
