package ru.dbotthepony.mc.otm.android.feature

import net.minecraft.nbt.CompoundTag
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.level.GameRules
import net.minecraftforge.event.entity.living.LivingHurtEvent
import ru.dbotthepony.mc.otm.config.AndroidConfig
import ru.dbotthepony.mc.otm.android.AndroidFeature
import ru.dbotthepony.mc.otm.capability.MatteryPlayerCapability
import ru.dbotthepony.mc.otm.registry.AndroidFeatures
import ru.dbotthepony.mc.otm.registry.StatNames
import ru.dbotthepony.mc.otm.core.nbt.set
import kotlin.math.roundToInt

class NanobotsRegenerationFeature(android: MatteryPlayerCapability) : AndroidFeature(AndroidFeatures.NANOBOTS_REGENERATION, android) {
	private var ticksPassed = 0
	private var healTicks = 0

	override fun tickServer() {
		if (ply.isHurt && ply.level().gameRules.getBoolean(GameRules.RULE_NATURAL_REGENERATION)) {
			ticksPassed++

			val waitTime = AndroidConfig.NanobotsRegeneration.COOLDOWN.getOrElse(healTicks) { AndroidConfig.NanobotsRegeneration.COOLDOWN.last() }

			if (ticksPassed > waitTime) {
				val missingHealth = (ply.maxHealth - ply.health).coerceAtMost(2f)
				val power = AndroidConfig.NanobotsRegeneration.ENERGY_PER_HITPOINT * missingHealth
				val extracted = android.androidEnergy.extractEnergy(power, false)

				if (extracted.isPositive) {
					healTicks = (healTicks + 1).coerceAtMost(level)
					val healed = (extracted / AndroidConfig.NanobotsRegeneration.ENERGY_PER_HITPOINT).toFloat()
					ply.heal(healed)
					(ply as ServerPlayer?)?.awardStat(StatNames.HEALTH_REGENERATED, (healed * 10f).roundToInt())
					ticksPassed = 0
				}
			}
		} else {
			ticksPassed = 0
			healTicks = 0
		}
	}

	override fun onHurt(event: LivingHurtEvent) {
		if (event.amount > 0f) {
			ticksPassed = 0
			healTicks = 0
		}
	}

	override fun serializeNBT(): CompoundTag {
		return super.serializeNBT().also {
			it["ticksPassed"] = ticksPassed
			it["healTicks"] = healTicks
		}
	}

	override fun deserializeNBT(nbt: CompoundTag) {
		super.deserializeNBT(nbt)
		ticksPassed = nbt.getInt("ticksPassed")
		healTicks = nbt.getInt("healTicks")
	}
}
