Scriptname _00E_FS_FortifySummonsSC extends activemagiceffect  

Actor Property PlayerREF Auto
Perk Property _00E_FS_PhasmalistEnchantment Auto

Actor Target

Event OnEffectStart(Actor akTarget, Actor akCaster)
	Target = akTarget

	If Target
		If PlayerREF == None
			PlayerREF = Game.GetPlayer()
		EndIf
		If _00E_FS_PhasmalistEnchantment == None
			_00E_FS_PhasmalistEnchantment = Game.GetFormFromFile(0x102F5A1, "Enderal - Forgotten Stories.esm") as Perk
		EndIf
		AdjustValues(True)
		RegisterForSingleUpdate(3)
	EndIf
EndEvent

Event OnUpdate()
	AdjustValues(False)
	RegisterForSingleUpdate(3)
EndEvent

Function AdjustValues(Bool bForceEnchantmentStrength)
	Float fNewModifier = PlayerREF.GetAV("FavorPointsBonus") / 100.0 
	Float fOldModifier = Target.GetAV("FavorPointsBonus") / 100.0

	If (fNewModifier != fOldModifier) || bForceEnchantmentStrength
		_00E_FS_PhasmalistEnchantment.SetNthEntryValue(0, 0, 1.0 + fNewModifier)
	EndIf

	If fNewModifier == fOldModifier
		Return ; Nothing changed
	EndIf

	Float fMaxHealth = GetTargetMaxValue("Health")
	Float fMaxMagicka = GetTargetMaxValue("Magicka")

	Target.SetAV("FavorPointsBonus", fNewModifier * 100.0)
	Target.ModAV("AttackDamageMult", fNewModifier - fOldModifier)

	if fMaxHealth > 0
		AdjustTargetMainValue("Health", "FavorsPerDay", fMaxHealth, fNewModifier)
	endif

	if fMaxMagicka > 0
		AdjustTargetMainValue("Magicka", "FavorsPerDayTimer", fMaxMagicka, fNewModifier)
	endif

EndFunction

Float Function GetTargetMaxValue(String sValueName)
	Float fValue = Target.GetAV(sValueName)
	Float fPercentage = Target.GetActorValuePercentage(sValueName)
	If fValue > 0.0 && fPercentage > 0.0
		Return Math.Ceiling(fValue / fPercentage)
	Else
		Return -1.0 ; We are dealing with bad numbers, nothing good would come out of (fValue / fPercentage)
	EndIf
EndFunction

Float Function AdjustTargetMainValue(String sValueName, String sStoreValueName, Float fMaxValue, Float fNewModifier)
	Float fNewBuff = Math.Floor(fMaxValue * fNewModifier)
	Float fOldBuff = Target.GetAV(sStoreValueName)
	If fNewBuff != fOldBuff
		Target.ModAV(sValueName, fNewBuff - fOldBuff)
		Target.SetAV(sStoreValueName, fNewBuff)
	EndIf
EndFunction