package ru.dbotthepony.mc.otm.item

import net.minecraft.ChatFormatting
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.chat.Component
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Rarity
import net.minecraft.world.item.TooltipFlag
import net.minecraft.world.level.Level
import net.minecraftforge.common.capabilities.ICapabilityProvider
import ru.dbotthepony.mc.otm.config.ConciseBalanceValues
import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.capability.*
import ru.dbotthepony.mc.otm.capability.energy.EnergyProducerItem
import ru.dbotthepony.mc.otm.capability.energy.ItemEnergyStorageImpl
import ru.dbotthepony.mc.otm.capability.energy.getBarColor
import ru.dbotthepony.mc.otm.capability.energy.getBarWidth
import ru.dbotthepony.mc.otm.config.ItemsConfig
import ru.dbotthepony.mc.otm.core.*
import ru.dbotthepony.mc.otm.core.math.Decimal

open class SingleUseBatteryItem(
	private val _capacity: () -> Decimal,
	private val _throughput: () -> Decimal? = { null },
	properties: Properties = Properties().stacksTo(1)
) : Item(properties) {
	constructor(values: ConciseBalanceValues, properties: Properties = Properties().stacksTo(1)) : this(values::capacity, values::throughput, properties)
	constructor(storage: Decimal, throughput: Decimal? = null, properties: Properties = Properties().stacksTo(1)) : this({ storage }, { throughput }, properties)

	val capacity get() = _capacity.invoke()
	val throughput get() = _throughput.invoke()

	override fun appendHoverText(
		itemStack: ItemStack,
		p_41422_: Level?,
		list: MutableList<Component>,
		p_41424_: TooltipFlag
	) {
		super.appendHoverText(itemStack, p_41422_, list, p_41424_)
		list.add(TranslatableComponent("otm.battery.single_use").withStyle(ChatFormatting.GRAY))
		ItemEnergyStorageImpl.appendHoverText(itemStack, list)
	}

	override fun initCapabilities(stack: ItemStack, nbt: CompoundTag?): ICapabilityProvider {
		return EnergyProducerItem(stack, capacity, throughput, initialBatteryLevel = capacity)
	}

	override fun isBarVisible(p_150899_: ItemStack): Boolean {
		return p_150899_.matteryEnergy != null
	}

	override fun getBarWidth(p_150900_: ItemStack): Int {
		return p_150900_.matteryEnergy?.getBarWidth() ?: super.getBarWidth(p_150900_)
	}

	override fun getBarColor(p_150901_: ItemStack): Int {
		return p_150901_.matteryEnergy?.getBarColor() ?: super.getBarColor(p_150901_)
	}
}

class ZPMItem : SingleUseBatteryItem(ItemsConfig.Batteries.ZPM, Properties().stacksTo(1).rarity(Rarity.EPIC)) {
	override fun appendHoverText(
		itemStack: ItemStack,
		p_41422_: Level?,
		list: MutableList<Component>,
		p_41424_: TooltipFlag
	) {
		super.appendHoverText(itemStack, p_41422_, list, p_41424_)
		list.add(TranslatableComponent("$descriptionId.description").withStyle(ChatFormatting.DARK_GRAY))
	}
}
