package ru.dbotthepony.mc.otm.capability.fluid

import net.minecraft.core.Direction
import net.minecraft.nbt.CompoundTag
import net.minecraft.world.item.BlockItem
import net.minecraft.world.item.ItemStack
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.common.capabilities.ForgeCapabilities
import net.minecraftforge.common.capabilities.ICapabilityProvider
import net.minecraftforge.common.util.LazyOptional
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.capability.IFluidHandler
import net.minecraftforge.fluids.capability.IFluidHandlerItem
import ru.dbotthepony.mc.otm.core.nbt.set
import ru.dbotthepony.mc.otm.core.tagNotNull
import java.util.function.IntSupplier

/**
 * Fluid handler for standalone items
 */
open class ItemMatteryFluidHandler(val itemStack: ItemStack, private val _capacity: IntSupplier) : AbstractMatteryFluidHandler(), IFluidHandlerItem, ICapabilityProvider {
	private val resolver = LazyOptional.of { this }

	override var fluid: FluidStack
		get() { return FluidStack.loadFluidStackFromNBT(itemStack.tag?.get("fluid") as? CompoundTag ?: return FluidStack.EMPTY) }
		set(value) { itemStack.tagNotNull["fluid"] = value.writeToNBT(CompoundTag()) }

	final override val capacity: Int
		get() = _capacity.asInt

	final override fun getContainer(): ItemStack {
		return itemStack
	}

	override fun <T : Any?> getCapability(cap: Capability<T>, side: Direction?): LazyOptional<T> {
		if (cap === ForgeCapabilities.FLUID_HANDLER_ITEM || cap === ForgeCapabilities.FLUID_HANDLER) {
			return resolver.cast()
		}

		return LazyOptional.empty()
	}

	override fun fill(resource: FluidStack, action: IFluidHandler.FluidAction): Int {
		if (itemStack.count != 1)
			return 0

		return super.fill(resource, action)
	}

	override fun drain(resource: FluidStack, action: IFluidHandler.FluidAction): FluidStack {
		if (itemStack.count != 1)
			return FluidStack.EMPTY

		return super.drain(resource, action)
	}

	override fun drain(maxDrain: Int, action: IFluidHandler.FluidAction): FluidStack {
		if (itemStack.count != 1)
			return FluidStack.EMPTY

		return super.drain(maxDrain, action)
	}
}
