package ru.dbotthepony.mc.otm.item

import net.minecraft.nbt.CompoundTag
import net.minecraft.network.chat.Component
import net.minecraft.world.InteractionResult
import net.minecraft.world.item.BlockItem
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.TooltipFlag
import net.minecraft.world.item.context.UseOnContext
import net.minecraft.world.level.Level
import net.minecraftforge.common.capabilities.ForgeCapabilities
import net.minecraftforge.common.capabilities.ICapabilityProvider
import ru.dbotthepony.mc.otm.block.decorative.FluidTankBlock
import ru.dbotthepony.mc.otm.block.entity.decorative.FluidTankBlockEntity
import ru.dbotthepony.mc.otm.capability.fluid.BlockMatteryFluidHandler
import ru.dbotthepony.mc.otm.capability.fluidLevel
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.ifPresentK
import java.util.function.IntSupplier

class FluidTankItem(block: FluidTankBlock, properties: Properties, val capacity: IntSupplier) : BlockItem(block, properties) {
	override fun initCapabilities(stack: ItemStack, nbt: CompoundTag?): ICapabilityProvider {
		return BlockMatteryFluidHandler.Item(stack, capacity, FluidTankBlockEntity.FLUID_KEY)
	}

	override fun onItemUseFirst(stack: ItemStack, pContext: UseOnContext): InteractionResult {
		if (pContext.player?.isCrouching == true)
			return InteractionResult.PASS

		val context = FluidCapsuleItem.Context(pContext.clickedPos, pContext.level.getBlockState(pContext.clickedPos), pContext.clickedFace)

		if (FluidCapsuleItem.canInteract(pContext.itemInHand, pContext.player ?: return InteractionResult.FAIL, context))
			return FluidCapsuleItem.interact(pContext.itemInHand, pContext.player!!, context)

		return super.onItemUseFirst(stack, pContext)
	}

	override fun getName(pStack: ItemStack): Component {
		pStack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM).ifPresentK {
			it.getFluidInTank(0).also {
				if (!it.isEmpty) {
					return TranslatableComponent("$descriptionId.named", it.displayName)
				}
			}
		}

		return super.getName(pStack)
	}

	override fun appendHoverText(pStack: ItemStack, pLevel: Level?, pTooltip: MutableList<Component>, pFlag: TooltipFlag) {
		super.appendHoverText(pStack, pLevel, pTooltip, pFlag)

		pStack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM).ifPresentK {
			it.fluidLevel(pTooltip)
		}
	}
}
