package ru.dbotthepony.mc.otm.container

import it.unimi.dsi.fastutil.objects.ObjectSpliterator
import it.unimi.dsi.fastutil.objects.ObjectSpliterators.AbstractIndexBasedSpliterator
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.capability.IFluidHandler
import java.util.Spliterator
import java.util.stream.Stream
import java.util.stream.StreamSupport

class FluidHandlerSpliterator(private val handler: IFluidHandler, offset: Int = 0, private val maxPos: Int = handler.tanks) : AbstractIndexBasedSpliterator<FluidStack>(offset) {
	init {
		require(offset in 0 until handler.tanks) { "Invalid offset $offset" }
		require(offset <= maxPos) { "offset <= maxPos: $offset > $maxPos!" }
		require(maxPos >= offset && maxPos in 0 .. handler.tanks) { "Invalid spliterator configuration: maxPos $maxPos offset $offset max tanks ${handler.tanks}" }
	}

	override fun get(location: Int): FluidStack {
		return handler[location]
	}

	override fun getMaxPos(): Int {
		return maxPos
	}

	override fun makeForSplit(pos: Int, maxPos: Int): ObjectSpliterator<FluidStack> {
		return FluidHandlerSpliterator(handler, pos, maxPos)
	}
}

fun IFluidHandler.spliterator(offset: Int = 0): Spliterator<FluidStack> = FluidHandlerSpliterator(this, offset)
fun IFluidHandler.stream(offset: Int = 0): Stream<FluidStack> = StreamSupport.stream(spliterator(offset), false)
