Scriptname _00E_PlayerSetUpScript extends ObjectReference  
{Initializes all the necessary Quests, maintains the player, contains various OnPlayerLoadGame() failsafes. This script is important for proper updating, do not overwrite it.}

Float Property CURRENT_PATCH_VERSION = 2.12 AutoReadOnly


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

Event OnInit()
	
	If self != (PlayerREF as ObjectReference)
		return
	EndIf

	; needs the IsInMenuMode() check to prevent stuck messages when FS is not loaded
	While Utility.IsInMenuMode()
		Utility.WaitMenuMode(0.1)
	EndWhile

	CheckForgottenStories()
	
	_00E_Func_CheckSKSE.Run()
	_00E_Func_CheckEnderalDLL.Run()

	If fPatchVersion == 0.00
		fPatchVersion = CURRENT_PATCH_VERSION
	EndIf
	
	GoToState("RealPlayer")
	PlayerREF.SetActorValue("speedMult", 95)
	PlayerREF.SetActorValue("Healrate", 0)
	
	EnableDisableKillmove()
	
	; Added in 1.5.8.0

	; starts all quests that are in the formlist
	Int iIndex = QuestsToStart.GetSize()
	While iIndex > 0
		iIndex -= 1
		Quest kQuest = QuestsToStart.GetAt(iIndex) as Quest
		kQuest.Start()
	endwhile

	If Game.GetModByName("Enderal_FS_More_Affinities.esp") != 255
		Game.QuitToMainMenu()
		Debug.MessageBox("Enderal_FS_More_Affinities.esp is outdated and does not work with Enderal SE. Please, uninstall or update the mod.")
	EndIf

EndEvent

Event OnPlayerLoadGame()
	If self == (PlayerREF as ObjectReference) ; A check just in case. Most likely this condition is always True
		CheckForgottenStories()
		
		_00E_Func_CheckSKSE.Run()
		_00E_Func_CheckEnderalDLL.Run()
	
		Maintenance()
		If GetState() != "RealPlayer" ; Post-1.2.5.0 version update
			GoToState("RealPlayer")
		EndIf
	EndIf
EndEvent

State RealPlayer

	;/ Event OnBeginState()
		Debug.Trace(self + ": OnBeginState RealPlayer")
	EndEvent /;

EndState


;=====================================================================================
;              							 2.0.6
;=====================================================================================

Function UpdateMQ12b_206()
	_00E_MQ12b_Functions MQ12bFunctions = Game.GetForm(0x2EBAD) as _00E_MQ12b_Functions
	Quest MQ15 = Game.GetFormFromFile(0x0002EBB0, "Skyrim.esm") as Quest
	If MQ12bFunctions.GetCurrentStageID() >= 135 && MQ15.GetCurrentStageID() < 5
		MQ12bFunctions.OldReenableDisabledNPC()
	EndIf
EndFunction


;=====================================================================================
;              							 2.0.8
;=====================================================================================

Function Update_208()
	; Obsolete abilities cleanup
	_00E_FS_NQ07_Functions FS_NQ07_Quest = Game.GetFormFromFile(0x0001CA09, "Enderal - Forgotten Stories.esm") as _00E_FS_NQ07_Functions
	Int iFS_NQ07Stage = FS_NQ07_Quest.GetCurrentStageID()
	If iFS_NQ07Stage >= 5 && iFS_NQ07Stage < 410
		FS_NQ07_Quest.UpdateAarosCarryTraySpell()
	Else
		RemoveObsoleteSpell(0x0009A893, "Skyrim.esm", 0x000F649A, "Skyrim.esm")
	EndIf

	RemoveObsoleteSpell(0x0010D339, "Skyrim.esm", 0x000F649A, "Skyrim.esm")
	RemoveObsoleteSpell(0x0006FFAF, "Skyrim.esm", 0x000F6498, "Skyrim.esm")
	RemoveObsoleteSpell(0x000F64A0, "Skyrim.esm", 0x000F6498, "Skyrim.esm")

	; Refill _00E_AnimTest_SC package arrays where needed
	FillAnimTestPackages(0x00137889, "Skyrim.esm", 0x00070657, "Skyrim.esm")
	FillAnimTestPackages(0x0013788A, "Skyrim.esm", 0x00070657, "Skyrim.esm")
	FillAnimTestPackages(0x0013789F, "Skyrim.esm", 0x00070657, "Skyrim.esm")
	FillAnimTestPackages(0x001378A2, "Skyrim.esm", 0x00070657, "Skyrim.esm")
	FillAnimTestPackages(0x001378AA, "Skyrim.esm", 0x00070657, "Skyrim.esm")
	FillAnimTestPackages(0x001378AB, "Skyrim.esm", 0x00070657, "Skyrim.esm")
	FillAnimTestPackages(0x00147E12, "Skyrim.esm", 0x00070657, "Skyrim.esm")
	FillAnimTestPackages(0x00147E14, "Skyrim.esm", 0x00070657, "Skyrim.esm")
	
	FillAnimTestPackages(0x0010D336, "Skyrim.esm", 0x00070645, "Skyrim.esm")
	FillAnimTestPackages(0x0010D33B, "Skyrim.esm", 0x00070645, "Skyrim.esm")
	FillAnimTestPackages(0x00147DEA, "Skyrim.esm", 0x00070645, "Skyrim.esm")
	FillAnimTestPackages(0x00147E37, "Skyrim.esm", 0x00070645, "Skyrim.esm")

	; "Gypsy minstrels" update
	Keyword performSpotKwd = Game.GetFormFromFile(0x000FB905, "Skyrim.esm") as Keyword
	(Game.GetFormFromFile(0x00044EBC, "Skyrim.esm") as _00E_BardPlayInstrumentScript).LinkedPlayMarkerKeyword = performSpotKwd

	(Game.GetFormFromFile(0x00046D79, "Skyrim.esm") as _00E_GypsyMinstrelsControlScript).UpdateWaypoint()
EndFunction

Function RemoveObsoleteSpell(Int idNPC, String esmNPC, Int idSpell, String esmSpell)
	Spell obsoleteSpell = Game.GetFormFromFile(idSpell, esmSpell) as Spell
	(Game.GetFormFromFile(idNPC, esmNPC) as Actor).RemoveSpell(obsoleteSpell)
EndFunction

Function FillAnimTestPackages(Int idNPC, String esmNPC, Int idPackage, String esmPackage)
	Package newPackage = Game.GetFormFromFile(idPackage, esmPackage) as Package
	(Game.GetFormFromFile(idNPC, esmNPC) as _00E_AnimTest_SC).UpdateFillPackages(newPackage)
EndFunction


;=====================================================================================
;              							 2.0.10
;=====================================================================================

Function Update_210()
	Spell abSoulcaller = Game.GetFormFromFile(0x002F0EA, "Enderal - Forgotten Stories.esm") as Spell
	If PlayerREF.HasSpell(abSoulcaller)
		PlayerREF.RemoveSpell(abSoulcaller)
		Utility.Wait(1)
		PlayerREF.AddSpell(abSoulcaller, False)
	EndIf

	Perk perkBloodlust = Game.GetFormFromFile(0x00069D38, "Skyrim.esm") as Perk
	_ResetPerk(perkBloodlust)

	_00E_PlayerhousingMaster.GetMaster().Update_209()

	; Previous versions may have silence tracks stuck
	Levelsystem.RemoveSilence()
EndFunction


;=====================================================================================
;              							 2.0.12
;=====================================================================================

Function Update_212()
	PlayerREF.AddPerk(Game.GetFormFromFile(0x14CF8, "Enderal - Forgotten Stories.esm") as Perk) ; _00E_SE_WerewolfBlockFurniturePerk
	PlayerREF.AddPerk(Game.GetFormFromFile(0x14CFA, "Enderal - Forgotten Stories.esm") as Perk) ; _00E_SE_DismantlePerk
	PlayerREF.AddPerk(Game.GetFormFromFile(0x14CF9, "Enderal - Forgotten Stories.esm") as Perk) ; _00E_SE_2_0_12_UpgradePerk
EndFunction


;=====================================================================================
;              							 ALL UPDATES                   					 
;=====================================================================================

Function EnableDisableKillmove()
	
	; it seems like that this ini setting does not do stuff by itself (or it is bugged)
	; therefore we need to read it from the file and change the global with which the killmoves are conditioned

	If Utility.GetINIBool("bVATSDisable:VATS") == false
		KillMove.SetValueInt(1)
	Else
		KillMove.SetValueInt(0)
	EndIf

EndFunction

Function SetAutoSaveInterval()
	
	; updates the autosave interval
	_00E_AutoSaveSystem_Functions AutoSaveSystem_Functions = Game.GetFormFromFile(0x00048141, "Skyrim.esm") as _00E_AutoSaveSystem_Functions
	AutoSaveSystem_Functions.UpdateAutoSaveInterval()
	
EndFunction

Function FailsafeMQ05PrologueAliases()

	; failsafe for issue 1536, fills empty aliases
	If MQ05PrologueFunctions == None
		MQ05PrologueFunctions = Game.GetForm(0x00033A5B) as _00E_MQ05Prologue_Functions
	EndIf
	MQ05PrologueFunctions.FillEmptyAliasesFailsafe()

EndFunction

Function RefreshMountNamesOnLoad()

	_00E_NQ06_Functions NQ06Functions = Game.GetForm(0x725BA) as _00E_NQ06_Functions
	NQ06Functions.RefreshNamesOnSaveLoad()

EndFunction

Function _ResetPerk(Perk p)
	If PlayerREF.HasPerk(p)
		PlayerREF.RemovePerk(p)
		PlayerREF.AddPerk(p)
	EndIf
EndFunction

Function ResetArmorWeightPerks()

	; Perks modifying armor weights need some push on each game load to work.
	; The push is needed only if the player is over-encumbered on game load. 
	; If the player is not over-encumbered, the push is not needed because checking the inventory, picking up items, sheathing/drawing a weapon will reset the perks anyway.
	If PlayerREF.IsOverEncumbered()
		_ResetPerk(_00E_Class_Keeper_P05_C_Conditioning)
		_ResetPerk(_00E_Class_Vagrant_P05_B_Lightweight)
	EndIf

EndFunction

;=====================================================================================
;              							 MAINTENANCE                   					 
;=====================================================================================

function CheckForgottenStories()
	; If Enderal - Forgotten Stories.esm is not loaded, kick the player back to main menu
	if (Game.GetForm(0x4320E) as GlobalVariable).GetValue() as Int != 1
		Utility.wait(2.0)
		Game.QuitToMainMenu()
		Debug.MessageBox("Enderal - Forgotten Stories.esm is not loaded! The game will not run properly. Open Data Files and enable it.")
		return
	EndIf
endfunction

Function Maintenance()
	
	if fPatchVersion <= 1.62
		Debug.MessageBox("A savegame was loaded which was made before the release of Enderal SE. In this save, several new features won't be available and there is a chance that you'll encounter grave bugs. Please, start a new game.")
		Game.QuitToMainMenu()
		return
	endif

	if fPatchVersion < CURRENT_PATCH_VERSION
		If fPatchVersion < 2.06
			UpdateMQ12b_206()
		EndIf
		If fPatchVersion < 2.08
			Update_208()
		EndIf
		If fPatchVersion < 2.10
			Update_210()
		EndIf
		If fPatchVersion < 2.12
			Update_212()
		EndIf
		fPatchVersion = CURRENT_PATCH_VERSION
	endif
	
	; changes to the actor value healrate will not persist in consecutive saves
	; every time a save gets loaded the healrate needs to be set to 0, otherwise it will go back again to default at 0.7
	; this is called before active magic effects of potions or spells are applied to the player which could also alter the value
	PlayerREF.SetActorValue("Healrate", 0)

	; Workaround for broken physics on loading saves, made on a mount
	If PlayerREF.IsOnMount()
		PlayerREF.Dismount()
	EndIf

	EnableDisableKillmove()
	
	ResetArmorWeightPerks()

	SetAutoSaveInterval()
	
	FailsafeMQ05PrologueAliases()
	
	RefreshMountNamesOnLoad()

	SendModEvent("Enderal_GameLoaded")

EndFunction

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

float fPatchVersion

_00E_MQ05Prologue_Functions Property MQ05PrologueFunctions Auto

Actor Property PlayerREF Auto

FormList Property QuestsToStart Auto

GlobalVariable Property KillMove Auto

Perk Property _00E_Class_Keeper_P05_C_Conditioning Auto
Perk Property _00E_Class_Vagrant_P05_B_Lightweight Auto

_00E_QuestFunctions Property Levelsystem Auto