package ru.dbotthepony.mc.otm.container

import it.unimi.dsi.fastutil.objects.ObjectIterators
import net.minecraft.world.Container
import net.minecraft.world.item.ItemStack
import ru.dbotthepony.mc.otm.core.collect.ContainerItemStackEntry
import ru.dbotthepony.mc.otm.core.collect.AwareItemStack

class ContainerIterator(private val container: Container, initialPosition: Int = 0) : ObjectIterators.AbstractIndexBasedListIterator<ItemStack>(0, initialPosition), MutableListIterator<ItemStack> {
	init {
		require(initialPosition in 0 .. container.containerSize) { "Invalid initial position: $initialPosition" }
	}

	override fun add(location: Int, k: ItemStack) {
		throw UnsupportedOperationException()
	}

	override fun set(location: Int, k: ItemStack) {
		container[location] = k
	}

	override fun remove(location: Int) {
		pos++
		container[location] = ItemStack.EMPTY
	}

	override fun get(location: Int): ItemStack {
		return container[location]
	}

	override fun getMaxPos(): Int {
		return container.containerSize
	}
}

class AwareContainerIterator(private val container: Container, initialPosition: Int = 0) : ObjectIterators.AbstractIndexBasedIterator<AwareItemStack>(0, initialPosition), Iterator<AwareItemStack> {
	init {
		require(initialPosition in 0 .. container.containerSize) { "Invalid initial position: $initialPosition" }
	}

	override fun remove(location: Int) {
		pos++
		container[location] = ItemStack.EMPTY
	}

	override fun get(location: Int): AwareItemStack {
		return ContainerItemStackEntry(location, container)
	}

	override fun getMaxPos(): Int {
		return container.containerSize
	}
}

@JvmOverloads
fun Container.iterator(initialPosition: Int = 0) = ContainerIterator(this, initialPosition)

@JvmOverloads
fun Container.awareIterator(initialPosition: Int = 0) = AwareContainerIterator(this, initialPosition)
