package ru.dbotthepony.mc.otm.container.util

import net.minecraft.world.Container
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
import ru.dbotthepony.mc.otm.container.IContainerSlot
import ru.dbotthepony.mc.otm.container.IMatteryContainer
import ru.dbotthepony.mc.otm.container.get
import ru.dbotthepony.mc.otm.core.collect.filter
import ru.dbotthepony.mc.otm.core.collect.map
import ru.dbotthepony.mc.otm.core.isNotEmpty

class SimpleContainerSlot(override val slot: Int, override val container: Container) : IContainerSlot {
	init {
		require(slot in 0 until container.containerSize) { "Slot out of bounds: $slot (container: $container with size ${container.containerSize})" }
	}

	override fun getFilter(): Item? {
		return null
	}

	override fun setFilter(filter: Item?): Boolean {
		return false
	}
}

fun Container.containerSlot(slot: Int): IContainerSlot {
	if (this is IMatteryContainer) {
		return containerSlot(slot)
	} else {
		return SimpleContainerSlot(slot, this)
	}
}

operator fun Container.iterator() = iterator(true)

fun Container.iterator(nonEmpty: Boolean): Iterator<ItemStack> {
	if (this is IMatteryContainer) {
		return iterator(nonEmpty)
	} else if (nonEmpty) {
		return (0 until containerSize).iterator().map { this[it] }.filter { it.isNotEmpty }
	} else {
		return (0 until containerSize).iterator().map { this[it] }
	}
}

fun Container.slotIterator(nonEmpty: Boolean = true): Iterator<IContainerSlot> {
	if (this is IMatteryContainer) {
		return slotIterator(nonEmpty)
	} else if (nonEmpty) {
		return (0 until containerSize).iterator().filter { this[it].isNotEmpty }.map { SimpleContainerSlot(it, this) }
	} else {
		return (0 until containerSize).iterator().map { SimpleContainerSlot(it, this) }
	}
}
