package ru.dbotthepony.kstarbound.defs

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.kstarbound.Starbound
import ru.dbotthepony.kstarbound.util.AssetPathStack
import ru.dbotthepony.kstarbound.util.sbIntern

data class AssetPath(val path: String, val fullPath: String) {
	constructor(path: String) : this(path, path)

	companion object : TypeAdapterFactory {
		override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
			if (type.rawType == AssetPath::class.java) {
				return object : TypeAdapter<AssetPath>() {
					private val strings = gson.getAdapter(String::class.java)

					override fun write(out: JsonWriter, value: AssetPath?) {
						if (value == null)
							out.nullValue()
						else
							out.value(value.fullPath)
					}

					override fun read(`in`: JsonReader): AssetPath? {
						val path = strings.read(`in`) ?: return null
						if (path == "") return null
						return AssetPath(path.sbIntern(), AssetPathStack.remap(path).sbIntern())
					}
				} as TypeAdapter<T>
			}

			return null
		}
	}
}
