package ru.dbotthepony.mc.otm.compat.mekanism

import mekanism.api.Action
import mekanism.api.AutomationType
import mekanism.common.capabilities.energy.MachineEnergyContainer
import mekanism.common.registries.MekanismItems
import mekanism.common.tile.TileEntityChargepad
import net.minecraft.ChatFormatting
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.player.Player
import net.minecraftforge.event.entity.player.ItemTooltipEvent
import ru.dbotthepony.mc.otm.capability.isMekanismLoaded
import ru.dbotthepony.mc.otm.capability.matteryPlayer
import ru.dbotthepony.mc.otm.core.TranslatableComponent

object MekanismHooks {
	@JvmStatic
	fun chargeAndroidFromPadHook(container: MachineEnergyContainer<TileEntityChargepad>, entity: LivingEntity) {
		if (entity !is Player) return

		if (entity.matteryPlayer?.isAndroid == true) {
			val androidEnergy = entity.matteryPlayer!!.androidEnergy

			val expectedAmount = container.energyPerTick
			val remaining = (androidEnergy.receiveEnergy(expectedAmount.toDecimal() * Mekanism2MatteryEnergyWrapper.mekanism2MtJ, true) * Mattery2MekanismEnergyWrapper.mtj2Mekanism).toFloatingLong()

			if (remaining.smallerThan(expectedAmount)) {
				val extracted = container.extract(expectedAmount.subtract(remaining), Action.EXECUTE, AutomationType.INTERNAL)

				if (!extracted.isZero) {
					androidEnergy.receiveEnergy(extracted.toDecimal() * Mekanism2MatteryEnergyWrapper.mekanism2MtJ, false)
				}
			}
		}
	}

	private val BLACKHOLE_IMMUNITY = TranslatableComponent("otm.item.blackhole_immunity").withStyle(ChatFormatting.DARK_GRAY)

	@JvmStatic
	fun tooltipEvent(event: ItemTooltipEvent) {
		if (!isMekanismLoaded) {
			throw IllegalStateException("Mekanism is not loaded!")
		}

		if (event.itemStack.`is`(MekanismItems.MODULE_GRAVITATIONAL_MODULATING.get())) {
			event.toolTip.add(BLACKHOLE_IMMUNITY)
		}
	}
}
