package ru.dbotthepony.kstarbound.math

import ru.dbotthepony.kommons.util.AABB
import ru.dbotthepony.kommons.util.AABBi
import ru.dbotthepony.kommons.vector.Vector2i
import ru.dbotthepony.kstarbound.world.ChunkPos

fun AABB.encasingIntAABB(): AABBi {
	return AABBi(
		Vector2i(roundByAbsoluteValue(mins.x), roundByAbsoluteValue(mins.y)),
		Vector2i(roundByAbsoluteValue(maxs.x), roundByAbsoluteValue(maxs.y)),
	)
}

private class Iterator<T>(private val aabb: AABBi, private val factory: (x: Int, y: Int) -> T) : kotlin.collections.Iterator<T> {
	private var x = aabb.mins.x
	private var y = aabb.mins.y
	private var next = true

	override fun hasNext(): Boolean {
		return next
	}

	override fun next(): T {
		if (!next)
			throw IllegalStateException()

		val obj = factory.invoke(x++, y)

		if (x > aabb.maxs.x) {
			x = aabb.mins.x

			if (++y > aabb.maxs.y) {
				next = false
			}
		}

		return obj
	}
}

val AABBi.vectors: kotlin.collections.Iterator<Vector2i> get() = Iterator(this, ::Vector2i)
val AABBi.chunkPositions: kotlin.collections.Iterator<ChunkPos> get() = Iterator(this, ::ChunkPos)
