package ru.dbotthepony.kstarbound.collect

class RandomListIterator<E>(private val elements: MutableList<E>, private var index: Int = 0) : MutableListIterator<E> {
	override fun hasPrevious(): Boolean {
		return this.index > 0
	}

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

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

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

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

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

	private var lastIndex = -1

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

	override fun remove() {
		elements.removeAt(lastIndex)
		lastIndex = -1
	}

	override fun set(element: E) {
		elements[lastIndex] = element
	}
}
