package ru.dbotthepony.kstarbound.math

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import ru.dbotthepony.kstarbound.math.vector.Vector2d

object AABBTypeAdapter : TypeAdapter<AABB>() {
	override fun write(out: JsonWriter, value: AABB) {
		`out`.beginArray()
		`out`.value(value.mins.x)
		`out`.value(value.mins.y)
		`out`.value(value.maxs.x)
		`out`.value(value.maxs.y)
		`out`.endArray()
	}

	override fun read(`in`: JsonReader): AABB {
		`in`.beginArray()
		val minX = `in`.nextDouble()
		val minY = `in`.nextDouble()
		val maxX = `in`.nextDouble()
		val maxY = `in`.nextDouble()
		`in`.endArray()

		val xMins = minX.coerceAtMost(maxX)
		val xMaxs = maxX.coerceAtLeast(minX)

		val yMins = minY.coerceAtMost(maxY)
		val yMaxs = maxX.coerceAtLeast(minY)

		return AABB(
			Vector2d(xMins, yMins),
			Vector2d(xMaxs, yMaxs),
		)
	}
}

