package ru.dbotthepony.kstarbound.json

import com.google.gson.JsonArray
import com.google.gson.JsonElement
import it.unimi.dsi.fastutil.objects.ObjectSpliterator
import it.unimi.dsi.fastutil.objects.ObjectSpliterators
import java.util.stream.Stream
import java.util.stream.StreamSupport

class JsonArraySpliterator(private val obj: JsonArray, offset: Int = 0, private val maxPos: Int = obj.size()) : ObjectSpliterators.AbstractIndexBasedSpliterator<JsonElement>(offset) {
	init {
		require(offset >= 0) { "Invalid offset $offset" }
		require(offset + maxPos <= obj.size()) { "$offset -> $maxPos while having only size of ${obj.size()}!" }
	}

	override fun get(location: Int): JsonElement {
		return obj[location]
	}

	override fun getMaxPos(): Int {
		return maxPos
	}

	override fun makeForSplit(pos: Int, maxPos: Int): ObjectSpliterator<JsonElement> {
		return JsonArraySpliterator(obj, pos, maxPos)
	}
}

fun JsonArray.elementSpliterator() = JsonArraySpliterator(this)
fun JsonArray.stream(): Stream<out JsonElement> = StreamSupport.stream(elementSpliterator(), false)
