package ru.dbotthepony.kstarbound.collect

class RandomListIterator<E>(private val elements: MutableList<E>, index: Int = 0) : MutableListIterator<E> {
	private var index = index - 1

	override fun hasPrevious(): Boolean {
		return this.index > 0
	}

	override fun nextIndex(): Int {
		return this.index + 1
	}

	override fun previous(): E {
		return elements[--this.index]
	}

	override fun previousIndex(): Int {
		return (this.index - 1).coerceAtLeast(-1)
	}

	override fun add(element: E) {
		elements.add(this.index++, element)
	}

	override fun hasNext(): Boolean {
		return this.index < elements.size - 1
	}

	override fun next(): E {
		return elements[++this.index]
	}

	override fun remove() {
		elements.removeAt(this.index--)
	}

	override fun set(element: E) {
		elements[this.index] = element
	}
}
