package ru.dbotthepony.mc.otm.item.armor

import net.minecraft.client.model.HumanoidModel
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.damagesource.DamageTypes
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.EquipmentSlot
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.item.*
import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions
import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent
import net.neoforged.neoforge.event.entity.living.LivingIncomingDamageEvent
import ru.dbotthepony.kommons.math.RGBAColor
import ru.dbotthepony.mc.otm.OverdriveThatMatters.loc
import ru.dbotthepony.mc.otm.client.model.TritaniumArmorModel
import ru.dbotthepony.mc.otm.registry.ClientExtensionsListener
import ru.dbotthepony.mc.otm.registry.game.MArmorMaterials
import ru.dbotthepony.mc.otm.registry.game.MItems

private object TritaniumArmorRenderProperties : IClientItemExtensions {
	override fun getHumanoidArmorModel(
		entityLiving: LivingEntity,
		itemStack: ItemStack,
		armorSlot: EquipmentSlot,
		_default: HumanoidModel<*>
	): HumanoidModel<*> {
		if (armorSlot === EquipmentSlot.LEGS) {
			return TritaniumArmorModel.getModelLegs()
		}

		return TritaniumArmorModel.getModel()
	}
}

class TritaniumArmorItem(slot: Type) : ArmorItem(MArmorMaterials.TRITANIUM, slot, Properties().stacksTo(1).rarity(Rarity.RARE).durability(slot.getDurability(48))),
	ClientExtensionsListener {
	override fun registerClientExtensions(event: RegisterClientExtensionsEvent) {
		event.registerItem(TritaniumArmorRenderProperties, this)
	}

	override fun getArmorTexture(
		stack: ItemStack,
		entity: Entity,
		slot: EquipmentSlot,
		layer: ArmorMaterial.Layer,
		innerModel: Boolean
	): ResourceLocation {
		return if (layer.dyeable()) TEXTURE_LOCATION_BASE else TEXTURE_LOCATION_OVERLAY
	}

	companion object {
		val TRITANIUM_COLOR = RGBAColor(157, 187, 204).toBGRA()
		val TEXTURE_LOCATION_BASE = loc("textures/models/armor/tritanium_armor_base.png")
		val TEXTURE_LOCATION_OVERLAY = loc("textures/models/armor/tritanium_armor_overlay.png")

		fun onHurt(event: LivingIncomingDamageEvent) {
			if (event.source.typeHolder().`is`(DamageTypes.SWEET_BERRY_BUSH) || event.source.msgId == "sweetBerryBush") {
				if (
					event.entity.getItemBySlot(EquipmentSlot.FEET).let { !it.isEmpty && it.item == MItems.TRITANIUM_BOOTS } &&
					event.entity.getItemBySlot(EquipmentSlot.LEGS).let { !it.isEmpty && it.item == MItems.TRITANIUM_PANTS }
				) {
					event.isCanceled = true
				}
			}
		}
	}
}
