package ru.dbotthepony.kstarbound.json

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import ru.dbotthepony.kstarbound.Starbound
import ru.dbotthepony.kstarbound.VersionRegistry

abstract class VersionedAdapter<T>(val name: String, val parent: TypeAdapter<T>) : TypeAdapter<T>() {
	override fun write(out: JsonWriter, value: T) {
		if (Starbound.IS_STORE_JSON) {
			VersionRegistry.make(name, parent.toJsonTree(value)).toJson(out)
		} else {
			parent.write(out, value)
		}
	}

	override fun read(`in`: JsonReader): T {
		if (Starbound.IS_STORE_JSON) {
			return VersionRegistry.load(name, `in`, parent)
		} else {
			return parent.read(`in`)
		}
	}
}
