Scriptname _00E_MAG_EldritchDamageConcSC extends activemagiceffect  

Import Math

;=====================================================================================
;              							EVENTS                    					 
;=====================================================================================

Event OnEffectStart(Actor akTarget, Actor akCaster)

	caster = akCaster

	; Pre-calculate caster's damage because GetMagnitude() in DealSelfDMG fails if the ME finishes before reaching that code.
	fCasterDamage = Self.GetMagnitude() / EldritchDamageDivider.GetValue()

EndEvent

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

	If (akProjectile == _00E_EldritchFlamesProjectile) || (akProjectile == _00E_MAGEldritchStormWaveProjectile)
		If caster == PlayerRef
			If _00E_EldritchDamageBlockerConc.GetValueInt() == 0 && bSelfDmgLocked == False
				bSelfDmgLocked = True
				_00E_EldritchDamageBlockerConc.SetValueInt(1)
				DealSelfDMG()
				_00E_EldritchDamageBlockerConc.SetValueInt(0)
				bSelfDmgLocked = False
			EndIf
		ElseIf caster
			If caster.IsInFaction(_00E_EldritchDamageFaction) == False && bSelfDmgLocked == False
				bSelfDmgLocked = True
				caster.SetFactionRank(_00E_EldritchDamageFaction, 0)
				DealSelfDMG()
				caster.RemoveFromFaction(_00E_EldritchDamageFaction)
				bSelfDmgLocked = False
			EndIf
		EndIf
	EndIf
	
EndEvent


;=====================================================================================
;              							FUNCTIONS                    					 
;=====================================================================================

Function DealSelfDMG()
	
	ParalyzeFxShader.Play(caster)

	If caster != PlayerRef
		caster.DamageAV("Health", fCasterDamage * 0.5) ; Deal half of fCasterDamage to NPCs
	Else
		caster.DamageAV("Health", fCasterDamage)
	EndIf
	
	Utility.Wait(1)
	
	ParalyzeFxShader.Stop(caster)
	
EndFunction


;=====================================================================================
;              							PROPERTIES                    					 
;=====================================================================================

Actor caster
Float fCasterDamage
Bool bSelfDmgLocked

Projectile Property _00E_EldritchFlamesProjectile Auto
Projectile Property _00E_MAGEldritchStormWaveProjectile Auto

GlobalVariable Property EldritchDamageDivider Auto
GlobalVariable Property _00E_EldritchDamageBlockerConc Auto
Faction Property _00E_EldritchDamageFaction Auto

EffectShader Property ParalyzeFxShader Auto

Actor Property PlayerRef Auto