package ru.dbotthepony.mc.otm.container

import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap
import net.minecraft.world.Container
import net.minecraft.world.item.ItemStack

class ShadowContainer(private val parent: Container) : IContainer by IContainer.wrap(parent) {
	private val shadowed = Int2ObjectArrayMap<ItemStack>(0)

	override fun clearContent() {
		shadowed.clear()
		parent.clearContent()
	}

	override fun isEmpty(): Boolean {
		return parent.isEmpty && shadowed.isEmpty()
	}

	override fun getItem(slot: Int): ItemStack {
		return shadowed[slot] ?: parent.getItem(slot)
	}

	override fun removeItem(slot: Int, count: Int): ItemStack {
		val shadow = shadowed[slot] ?: return parent.removeItem(slot, count)
		val copy = shadow.copyWithCount(shadow.count.coerceAtLeast(count))
		shadow.split(count)
		if (shadow.isEmpty) shadowed[slot] = ItemStack.EMPTY
		return copy
	}

	override fun removeItemNoUpdate(slot: Int): ItemStack {
		shadowed[slot] ?: return parent.removeItemNoUpdate(slot)
		val old = shadowed[slot]
		shadowed[slot] = ItemStack.EMPTY
		return old!!
	}

	override fun setItem(slot: Int, item: ItemStack) {
		shadowed[slot] = item
	}

	companion object {
		fun shadow(container: Container, slot: Int, itemStack: ItemStack): Container {
			return ShadowContainer(container).also { it[slot] = itemStack }
		}
	}
}
