package ru.dbotthepony.mc.otm.item

import net.minecraft.ChatFormatting
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Rarity
import net.neoforged.neoforge.capabilities.Capabilities
import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent
import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.energy.EnergyProducerItem
import ru.dbotthepony.mc.otm.capability.energy.getBarColor
import ru.dbotthepony.mc.otm.capability.energy.getBarWidth
import ru.dbotthepony.mc.otm.capability.matteryEnergy
import ru.dbotthepony.mc.otm.config.EnergyBalanceValues
import ru.dbotthepony.mc.otm.config.ItemsConfig
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.math.Decimal
import ru.dbotthepony.mc.otm.registry.CapabilitiesRegisterListener

open class SingleUseBatteryItem(
	private val _capacity: () -> Decimal,
	private val _throughput: () -> Decimal? = { null },
	properties: Properties = Properties().stacksTo(1)
) : MatteryItem(properties), CapabilitiesRegisterListener {
	constructor(values: EnergyBalanceValues, properties: Properties = Properties().stacksTo(1)) : this(values::energyCapacity, values::energyThroughput, 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()

	init {
		tooltips.add(TranslatableComponent("otm.battery.single_use").withStyle(ChatFormatting.GRAY))
		tooltips.itemEnergy()
	}

	override fun registerCapabilities(event: RegisterCapabilitiesEvent) {
		event.registerItem(MatteryCapability.ITEM_ENERGY, { o, _ -> EnergyProducerItem(o, capacity, throughput, initialBatteryLevel = capacity) }, this)
		event.registerItem(Capabilities.EnergyStorage.ITEM, { o, _ -> EnergyProducerItem(o, capacity, throughput, initialBatteryLevel = capacity) }, this)
	}

	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)) {
	init {
		tooltips.add(TranslatableComponent("$descriptionId.description").withStyle(ChatFormatting.DARK_GRAY))
	}
}
