Scriptname xMATHICombatLogic extends activemagiceffect  

perk property xmaDexRemovingTheScaffold auto
perk property xmaDexMonkeyGrip auto

perk property xmaLIAEndeavor0 auto
perk property xmaLIAEndeavor1 auto

spell property xMALIAEndeavor0Spell Auto
spell property xMALIAEndeavor1Spell Auto

actor target = none

keyword property xmaweaptypefist auto

Event OnHit(ObjectReference akAggressor, Form akSource, Projectile akProjectile, bool abPowerAttack, bool abSneakAttack, bool abBashAttack, bool abHitBlocked)

	gotoState("busy")
	
	actor att = (akAggressor as actor)
	Weapon w = aksource as weapon

	if att && w && w.hasKeyword(xmaweaptypefist)

		;; monkey grip

		if att.hasperk(xmadexmonkeygrip) && abHitBlocked
			armor shield = target.getEquippedShield()

			If (shield)
				target.unequipItem(shield, false)
				target.removeitem(shield,1)
				att.additem(shield,1)
			endif
		endif

		;; removing the scaffold

		if att.hasperk(xmadexremovingthescaffold) && !abHitBlocked
			;it looks like Helmet and Gantlets are not in correct slots.
			;It's better to add these lines of code instead of replacing the old ones.
			;This way we are sure this will always work
			Armor arms = target.GetWornForm(0x00000010) as armor	; Forearms
			if !arms
				arms = target.GetWornForm(0x00000008) as armor		; Hands
			endif
			Armor helm = target.GetWornForm(0x00000001) as armor	; Head
			if !helm
				helm = target.GetWornForm(0x00000002) as armor		;Hair
			endif
			Armor leg = target.GetWornForm(0x00000080) as armor
			Armor body = target.GetWornForm(0x00000004) as armor

			if arms
				target.unequipItem(arms, false)
				target.removeitem(arms,1)
				att.additem(arms,1)
			elseif helm
				target.unequipItem(helm, false)
				target.removeitem(helm,1)
				att.additem(helm,1)
			elseif leg
				target.unequipItem(leg, false)
				target.removeitem(leg,1)
				att.additem(leg,1)
			elseif body
				target.unequipItem(body, false)
				target.removeitem(body,1)
				att.additem(body,1)

			endif

		endif
	endif

	if !abHitBlocked
		if target.hasperk(xMAliaEndeavor1)
			xMAliaEndeavor1Spell.cast(target, target)
		elseif target.hasperk(xMAliaEndeavor0)
			xMAliaEndeavor0Spell.cast(target, target)
		endif 
	endif

	gotoState("")

EndEvent

State busy
	Event OnHit(ObjectReference akAggressor, Form akSource, Projectile akProjectile, bool abPowerAttack, bool abSneakAttack, bool abBashAttack, bool abHitBlocked)
	EndEvent
EndState


Event OnEffectStart(actor t, actor c)
	target = t
EndEvent

Event OnEffectFinish(actor t, actor c)
	target = none
EndEvent