package ru.dbotthepony.mc.otm.compat.adastra

import earth.terrarium.ad_astra.AdAstra
import earth.terrarium.ad_astra.common.data.Planet
import earth.terrarium.ad_astra.common.data.PlanetData
import earth.terrarium.ad_astra.common.item.armor.SpaceSuit
import earth.terrarium.ad_astra.common.registry.ModDamageSources
import net.minecraft.world.entity.player.Player
import net.minecraftforge.event.entity.living.LivingHurtEvent
import net.minecraftforge.fml.ModList
import ru.dbotthepony.mc.otm.capability.MatteryPlayerCapability
import ru.dbotthepony.mc.otm.capability.matteryPlayer
import ru.dbotthepony.mc.otm.config.ServerCompatConfig
import ru.dbotthepony.mc.otm.core.damageType
import ru.dbotthepony.mc.otm.registry.MDamageTypes
import ru.dbotthepony.mc.otm.registry.MItems
import ru.dbotthepony.mc.otm.registry.MatteryDamageSource

val isAdAstraLoaded by lazy {
	ModList.get().isLoaded(AdAstra.MOD_ID)
}

// для надёжности
fun onDamageEvent(event: LivingHurtEvent) {
	check(isAdAstraLoaded) { "Ad Astra is not loaded!" }
	val ply = event.entity as? Player ?: return

	if (ServerCompatConfig.AdAstra.ANDROIDS_DO_NOT_NEED_OXYGEN) {
		if (ply.matteryPlayer?.isAndroid != true) return

		if (event.source.`is`(ModDamageSources.OXYGEN)) {
			event.amount = 0f
			event.isCanceled = true
		}
	}
}

fun onMatteryTick(event: MatteryPlayerCapability.PostTick) {
	check(isAdAstraLoaded) { "Ad Astra is not loaded!" }

	if (
		ServerCompatConfig.AdAstra.ANDROID_COSMIC_RAYS &&
		!event.player.abilities.invulnerable &&
		event.capability.isAndroid &&
		!PlanetData.getPlanetFromLevel(event.level.dimension()).map(Planet::hasAtmosphere).orElse(true)
	) {
		val rand = event.level.random

		val noSpacesuits = event.player.armorSlots.count { it.item !is SpaceSuit }
		val yesTritanium0 = if (!ServerCompatConfig.AdAstra.TRITANIUM_ARMOR_PROTECTS_AGAINST_COSMIC_RAYS) 0.0 else event.player.armorSlots.count { it.item in MItems.TRITANIUM_ARMOR } * 0.75
		val yesTritanium1 = if (!ServerCompatConfig.AdAstra.TRITANIUM_ARMOR_PROTECTS_AGAINST_COSMIC_RAYS) 0.0 else event.player.armorSlots.count { it.item in MItems.SIMPLE_TRITANIUM_ARMOR } * 0.2
		val yesTritanium = yesTritanium0 + yesTritanium1

		if (rand.nextDouble() <= (noSpacesuits - yesTritanium) * ServerCompatConfig.AdAstra.ANDROID_COSMIC_RAYS_CHANCE) {
			event.player.hurt(MatteryDamageSource(event.level.registryAccess().damageType(MDamageTypes.COSMIC_RAYS)), 1f)
		}
	}
}
