local function doFadeWipe(state)
  fadeWipe = celeste.FadeWipe(engine.Scene, state, nil)
  engine.Scene:Add(fadeWipe)
  fadeWipe.duration = 2
  fadeWipe.EndTimer = 1
end

local luaCutscenesUtils = require("#Celeste.Mod.MaxHelpingHand.Module.LuaCutscenesUtils")

local Audio = require("#celeste.Audio")

local lua_helper = celeste.Mod.LuaCutscenes.LuaHelper

local function makeCoroutine(func)
  return monocle.Coroutine(lua_helper.LuaCoroutineToIEnumerator(coroutine.create(func)))
end

local function pressbasil()
  wait(1.75)
  elevator:PlayAnimation("pressbasil")
  wait(0.6)
  sfxpressbasil = Audio.Play("event:/game/WanderBDay/omori_elevatorshut", elevator.Position)
end

local function closeelevator()
  player.ForceCameraUpdate = false
  local contagem = 0
  while contagem < 1 do
    coroutine.yield(celeste.CutsceneEntity.CameraTo(vector2(4824, 5999), 0, monocle.Ease.Linear, 0))
    wait()
    coroutine.yield(celeste.CutsceneEntity.CameraTo(vector2(4824, 5997), 0, monocle.Ease.Linear, 0))
    wait()
    contagem = contagem + 1
  end
end


function onBegin()

  if getFlag("outelevator") then

    disablePause()
    disableMovement()
    basil = celeste.Mod.MaxHelpingHand.Entities.MoreCustomNPC.GetNPC("basil")
    basil:RemoveSelf()
    player.ForceCameraUpdate = true
    elevator = celeste.Mod.MaxHelpingHand.Entities.MoreCustomNPC.GetNPC("elevator")
    elevator.Position = vector2(4840, 6121)
    elevator.Depth = 1001
    elevator:PlayAnimation("stay_open")

    doFadeWipe(true)
    wait(1.5)

    waitingCoroutine = makeCoroutine(pressbasil)
    cutsceneEntity:Add(waitingCoroutine)
    wait(1)

    walk(100)
    wait(0.5)

    player.Facing = getEnum("Celeste.Facings", "Left")
    wait(0.5)

    elevator:PlayAnimation("shakebasil")
    wait(1)

    coroutine.yield(luaCutscenesUtils.SayWithDifferentFont("OMORI_GAME", "CBR_BlackSpace_door2_elevator_basil3"))
    wait(0.5)

    sfxcloseelevatoronbasil = Audio.Play("event:/game/WanderBDay/omori_elevatorshut_crush", elevator.Position)
    closeelevator()
    player.ForceCameraUpdate = true
    setFlag("stopmusic2")
    elevator:PlayAnimation("killbasil")
    wait(5)

    coroutine.yield(luaCutscenesUtils.SayWithDifferentFont("OMORI_GAME", "CBR_BlackSpace_door2_elevator_basil4"))
    wait(1)

    walk(15)
    wait(1)

    setFlag("outelevator", false)
    setFlag("enddoor2")
    enableMovement()
    enablePause()

  end

end