Scriptname _00E_MQ05_Functions extends Quest Conditional

Import _00E_QuestFunctions
Import Utility

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

Function SetUp()

	_00E_MC_CaliaREF.Enable(false)
	_00E_MC_CaliaREF.EvaluatePackage()
	_00E_MQ05_DunwarREF.Enable(false)
	_00E_MQ05_DunwarREF.EvaluatePackage()
	_00E_MC_JorrekRef.Enable(false)
	_00E_MC_JorrekRef.EvaluatePackage()

	_00E_MC_CaliaREF.SetOutfit(_25E_HolyOrder_NoviceOutfitNoHelmet)

EndFunction

Function UpdateStage()

    if GetStage() == 15
        SetStage(17)
    Elseif GetStage() == 17
        SetStage(20)
    EndIf

EndFunction

Function RemovePackage()

    PlayerREF.RemoveItem(_00E_MQ05_BartarrPackage, 1)

EndFunction

Function StartIntroductionScene()

    SetObjectiveCompleted(17)
    MQ05_SC1_JorrekIntroducesPlayer.ForceStart()
    
EndFunction

function PlayerAIWalkStop()

    PlayerREF.PlayIdle(IdleWalkingCameraEnd)
    Game.EnablePlayerControls(abMovement = false, abFighting = false, abCamSwitch = false, abLooking = true, abSneaking = false, abmenu = false, abactivate = false, abjournaltabs = false)
    Game.SetPlayerAIDriven(False)
endFunction

function PlayerAIWalkStart()
    Game.DisablePlayerControls(abLooking = True)
    PlayerREF.PlayIdle(IdleWalkingCameraStart)
endFunction

Function StartVision()

    Levelsystem.VisionEffectTimestop()
    MQ05_SC3_Vision.ForceStart()

EndFunction

Function StopVision()

    Levelsystem.VisionEffectTimestopStop()
    Levelsystem.UpdateSpeed(PlayerREF)
    MQ05_SC3_Vision.Stop()
    Game.EnablePlayerControls()
    Game.SetPlayerAIDriven(False)
    
EndFunction

Function GroupSpotsMerchantScene()

	PosessedMerchant.GetActorReference().Enable()
    MQ05_SC4_GroupSpotsPosessedMerchant.ForceStart()

EndFunction

Function GroupConfrontsMerchantScene()

    MQ05_SC6_MerchantConfrontation.ForceStart()
	SetCompanions(false)

EndFunction

Function UntoggleMerchantGhost()

    PosessedMerchant.GetActorReference().SetGhost(False)

EndFunction

Function KillMerchant()

    MAGShockExpImod.Apply()
    PosessedMerchant.GetReference().KnockAreaEffect(1, 1024)
    _00E_MQ05_DunwarREF.PushActorAway(PosessedMerchant.GetActorReference(), 4.0)
    PlayerREF.SetGhost(False)
    _00E_MQ05_MerchantDeathM.Play(PosessedMerchant.GetReference())
    Wait(0.5)
    GroupConfrontsMerchantScene02()
    
EndFunction

Function KillMerchantFailsave()

    Actor akMerchant = PosessedMerchant.GetActorReference()
    akMerchant.SetGhost(False)
    akMerchant.GetActorBase().SetEssential(False)
    Wait(0.2)
    akMerchant.KillEssential(akMerchant)
    ObjectReference SkyMarker = akMerchant.PlaceAtMe(XMarkerHeading)
    SkyMarker.MoveTo(akMerchant, 0.0 , 0.0, 500)
    _00E_MQ05_DunwarLighting.RemoteCast(SkyMarker, akMerchant, akMerchant)
    SkyMarker.Delete()
    SetStage(80)
    
EndFunction

Function GroupConfrontsMerchantScene02()

    MQ05_SC7_MerchantConfrontation02.ForceStart()
	
EndFunction

Function RemoveSilence()

	_00E_SilenceTransitionHighPriority.Remove()

EndFunction

Function StartApproachOnRitualSiteScene()

	MQ05_SC08_TriggerREF.Enable()
	SetCompanions(true)

EndFunction

Function StartRitualScene()
	
	; just in case
	If MQ05_SC08_TriggerREF.IsEnabled()
		MQ05_SC08_TriggerREF.Disable()
	EndIf

	Game.RequestAutoSave()
    _00E_SilenceTransitionHighPriority.Add()
	SetCompanions(false)
    MQ05_SC9_DiscussionAndRitual.ForceStart()
	
	UnsummonApparitionIfExists()
	_FS_TheriantrophistControlQuest.TransformBackIfTransformed()
    
EndFunction

Function GivePlayerPotion()
    PlayerREF.AddItem(_00E_MQ05_RitualDrinkBottle, 1, false)
	SetCompanions(true)
EndFunction

Function SetCompanions(bool bCompanion)
	
	If bCompanion == true
		SetNPCAsCompanion(_00E_MC_CaliaREF, true, 300, 200, 100)
		SetNPCAsCompanion(_00E_MQ05_DunwarREF, true, 250, 200, 100)
		SetNPCAsCompanion(_00E_MC_JorrekRef, true, 350, 300, 100)
	Else 
		SetNPCAsCompanion(_00E_MC_CaliaREF, false)
		SetNPCAsCompanion(_00E_MQ05_DunwarREF, false)
		SetNPCAsCompanion(_00E_MC_JorrekRef, false)
	EndIf

EndFunction

Function PlayerDrinksPotion()

	_FS_TheriantrophistControlQuest.TransformBackIfTransformed()

	_00E_TeleportGlobal.SetValue(1)
    _00E_Meditate_Allowed.SetValueInt(0)
    Game.ForceThirdPerson()
    debug.SendAnimationEvent(PlayerREF as objectreference, "IdleDrinkPotion")
    Game.GetPlayer().RemoveItem(_00E_MQ05_RitualDrinkBottle, 1)
    Wait(5)
    Game.ForceFirstPerson()
    PlayerREF.PlayIdle(TG05_KnockOut)
    TG05SequenceImod.Apply()
    MAGVampireSunlight.Play(PlayerREF)
	Wait(3.2)
	FadeToBlackHoldImod.Apply()
	_00E_NPCKillBodyfall.Play(PlayerREF)
    Wait(2)
	
	Levelsystem.RemoveAllItemsSafeVersion(MQ05Container)
	
    PlayerREF.AddItem(ClothesPrisonerRags, 1, true)
    PlayerREF.EquipItem(ClothesPrisonerRags)
    PlayerREF.AddItem(_01E_01Messer, 1, true)
    PlayerREF.EquipItem(_01E_01Messer)
    PlayerREF.MoveTo(MQ05_JailPlayerStartMarker)
	FadeToBlackHoldImod.Remove()
    TG05SequenceImod.Remove()
    _00E_WakeUp.Apply()
    PlayerREF.PlayIdle(Idle_1stPersonWoozyGetUpFromBed)
    Wait(5)
    Game.EnablePlayerControls()
    Game.SetPlayerAIDriven(False)
    Self.SetStage(95)
    if Ryon.GetReference().GetParentCell() != PlayerREF.GetParentCell()
        ; Failsave for some weird cases where Aixon is missing. I
        ; hope this solves http://sureai.net:9898/browse/ERB-1794 .
        Debug.Trace("MQ05: Aixon forcibly moved to player cell!")
        Ryon.GetReference().MoveTo(PlayerREF)
    else
        Debug.Trace("MQ05: Aixon correctly located in player cell.")
    endif
    _00E_SilenceTransitionHighPriority.Remove()
	Levelsystem.ResumeRandomHeadTracking()
	Game.RequestAutoSave()
    
EndFunction

Function DisableGhostDoor()

    Game.DisablePlayerControls()
    _00E_MagConjureReanimate.Play(playerREF)
    _00E_MQ05_SurrealDisappearance.Apply()
    Wait(2.6)
    _00E_MQ05_GhostSound.Play(PlayerREF)
    MQ05_D6_JailDoor.Enable(False)
    Wait(4.5)
    Self.SetStage(110)

EndFunction

Function StartFinalScene()

    Game.ForceThirdPerson()
    PlayerAIWalk(True)

    ; Kill all the ghosts, to avoid confusing Aixon's AI.
    int iIndex = _00E_MQ05_GhostsList.GetSize()
    while iIndex > 0
        iIndex -= 1
        Actor akActor = _00E_MQ05_GhostsList.GetAt(iIndex) as Actor
        akActor.Kill()
    endwhile

    MQ05_SC14_PlayerWalksIntoCell.ForceStart()
    
    ; Timer failsave for the case when the player or Aixon takes too
    ; long (i.e., usually, fails) to enter the cell.
    ; This should solve http://sureai.net:9898/browse/ERB-674 and
    ; part of http://sureai.net:9898/browse/ERB-823 .
    Wait(10)
    If MQ05_SC14_PlayerWalksIntoCell.IsPlaying()
        Debug.Trace("MQ05: Ryon and player forcefully moved back to cell!")
        Self.SetStage(125)
        MQ05_SC14_PlayerWalksIntoCell.Stop()
        Ryon.GetReference().MoveTo(MQ05_SC14_AixonEndMarker)
        PlayerREF.MoveTo(MQ05_SC14_AixonEndMarker)
    EndIf

EndFunction

Function DisableGhostDoorFinal()

    _00E_MagConjureReanimate.Play(playerREF)
    _00E_MQ05_SurrealDisappearance.Apply()
    Wait(2.6)

    _00E_MQ05_GhostSound.Play(PlayerREF)
    MQ05_D7_JailDoorFinal.Enable(False)
    Wait(4.5)
    Self.SetStage(130)
    Ryon.GetReference().MoveTo(MQ05_SC14_AixonEndMarker)
    
EndFunction

Function StartAixonScene()

	Actor akRyon = Ryon.GetActorReference()

    akRyon.StopCombat()
    akRyon.EvaluatePackage()
    ; Restore Ryon's health to above 0 if he's bleeding out. 
    ; This fixes him not speaking all his lines in the followup scene sometimes.
    ; The code was copied from DGIntimidateQuestScript.
	If akRyon.IsBleedingOut()
		Float bleederHealth = akRyon.GetActorValue("health")
		If bleederHealth < 1
			bleederHealth = 10 - bleederHealth
			akRyon.RestoreActorValue("health", bleederHealth)
		EndIf
	EndIf

    MQ05_SC15_AixoNDisappear.ForceStart()

    akRyon.Say(MQ05_D8_2)
    Wait(3)
    _00E_AMBHorrorVoicesNoLoopM.Play(PlayerREF)
    Wait(15)
    _00E_MAGEldritchExplosionM.Play(PlayerREF)
    FadeToWhiteHoldImod.ApplyCrossFade()
    Wait(5)
	
	Levelsystem.RemoveAllItemsSafeVersion(None)
	Self.SetStage(150)

EndFunction

Function CompleteQuest()

    Levelsystem.RemoveSilence()

    If CQJ01_SC01_DancingNomadScene.IsPlaying()
        CQJ01_SC01_DancingNomadScene.Stop()
    EndIf
    
    If _00E_MC_YuslanRef.IsDisabled()
        _00E_MC_YuslanRef.Enable()
    EndIf
    
    Levelsystem.GiveEp(__Config_RewardEXP)
    
    If MQ05Prologue_SC2.IsPlaying()
        MQ05Prologue_SC2.Stop()
    EndIf
    
    If MQ05_SC09_DiscussionAndRitual.IsPlaying()
        MQ05_SC09_DiscussionAndRitual.Stop()
    EndIf
    
    If MQ03_SC4_KonstantinExaminesPlayer.IsPlaying()
        MQ03_SC4_KonstantinExaminesPlayer.Stop()
    EndIf

    _00E_Meditate_Allowed.SetValueInt(1)
    
    MQ06.Start()
    
EndFunction

Function StopRandomHeadTracking()
    Levelsystem.StopRandomHeadTracking()
EndFunction


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


int Property __Config_RewardEXP = 350 Auto
{How much EXP is granted upon completion}

_00E_QuestFunctions Property Levelsystem Auto

bool Property bSpokenWithCalia Auto Conditional Hidden
bool Property bSpokenWithDunwar Auto Conditional Hidden

idle property IdleWalkingCameraEnd auto
idle property IdleWalkingCameraStart auto
Idle Property TG05_KnockOut Auto
Idle Property Idle_1stPersonWoozyGetUpFromBed Auto
actor property PlayerREF auto

Actor Property _00E_MC_YuslanRef Auto

Armor Property ClothesPrisonerRags Auto
Weapon Property _01E_01Messer Auto

MiscObject Property _00E_MQ05_RitualDrinkBottle Auto
MiscObject Property _00E_MQ05_BartarrPackage Auto 

MusicType Property _00E_SilenceTransitionHighPriority Auto

GlobalVariable Property _00E_TeleportGlobal Auto
GlobalVariable Property _00E_Meditate_Allowed Auto

Actor Property _00E_MQ05_DunwarREF Auto
Actor Property _00E_MC_CaliaREF Auto
Actor Property _00E_MC_JorrekRef Auto

ReferenceAlias Property Dunwar Auto
ReferenceAlias Property Calia Auto
ReferenceAlias Property Jorrek Auto
ReferenceAlias Property PosessedMerchant Auto
ReferenceAlias Property Ryon Auto
Topic Property MQ05_D8_2 Auto

Scene Property MQ05_SC1_JorrekIntroducesPlayer Auto
Scene Property MQ05_SC3_Vision Auto
Scene Property MQ05_SC4_GroupSpotsPosessedMerchant Auto
Scene Property MQ05_SC6_MerchantConfrontation Auto
Scene Property MQ05_SC7_MerchantConfrontation02 Auto
Scene Property MQ05_SC9_DiscussionAndRitual Auto
Scene Property MQ05_SC14_PlayerWalksIntoCell Auto
Scene Property MQ05_SC15_AixoNDisappear Auto
Scene Property CQJ01_SC01_DancingNomadScene Auto
Scene Property MQ05Prologue_SC2 Auto
Scene Property MQ05_SC09_DiscussionAndRitual Auto
Scene Property MQ03_SC4_KonstantinExaminesPlayer Auto

Sound Property _00E_MQ05_GhostSound Auto
Sound Property _00E_MagConjureReanimate Auto
Sound Property _00E_AMBHorrorVoicesNoLoopM Auto
Sound Property _00E_MAGEldritchExplosionM Auto
Sound Property _00E_MQ05_MerchantDeathM Auto
Sound Property MAGVampireSunlight Auto
Sound Property _00E_NPCKillBodyfall Auto

Static Property XMarkerHeading Auto

Outfit Property _25E_HolyOrder_NoviceOutfitNoHelmet Auto

ImageSpaceModifier Property TG05SequenceImod Auto
ImageSpaceModifier Property _00E_WakeUp Auto
ImageSpaceModifier Property _00E_MQ05_SurrealDisappearance Auto
ImageSpaceModifier Property FadeToWhiteHoldImod Auto
ImageSpaceModifier Property FadeToBlackHoldImod Auto
ImageSpaceModifier Property MAGShockExpImod Auto

spell property _00E_MQ05_DunwarLighting auto

ObjectReference Property MQ05Container Auto
ObjectReference Property MQ05_JailPlayerStartMarker Auto
ObjectReference Property MQ05_D6_JailDoor Auto
ObjectReference Property MQ05_D7_JailDoorFinal Auto
ObjectReference Property MQ05_SC14_AixonEndMarker Auto
ObjectReference Property MQ05_SC08_TriggerREF Auto

Quest Property MQ06 Auto

Formlist Property _00E_MQ05_GhostsList Auto