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.Vector2i

object AABBiTypeAdapter : TypeAdapter<AABBi>() {
	override fun write(out: JsonWriter, value: AABBi) {
		`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): AABBi {
		`in`.beginArray()
		val minX = `in`.nextInt()
		val minY = `in`.nextInt()
		val maxX = `in`.nextInt()
		val maxY = `in`.nextInt()
		`in`.endArray()

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

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

		return AABBi(
			Vector2i(xMins, yMins),
			Vector2i(xMaxs, yMaxs),
		)
	}
}