local coroutineEntity = monocle.Entity()

local vector2 = require("#microsoft.xna.framework.vector2")

local badeline = nil

local function badeline_appears(right_side)
  -- determine the position and flipping properties
  local pos_x, scale
  if right_side then
    pos_x = player.Position.X - 18
    scale = 1
  else
    pos_x = player.Position.X + 38
    scale = -1
  end
  local pos_y = player.Position.Y - 8

  -- create and add a new badeline dummy entity
  badeline = celeste.BadelineDummy(vector2(pos_x, pos_y))
  badeline.Sprite.Scale.X = scale
  getLevel():Add(badeline)

  -- play sound + effect
  getLevel().Displacement:AddBurst(badeline.Center, 0.5, 8, 32, 0.5)
  playSound("event:/char/badeline/maddy_split", badeline.Position)

  -- wait until the next frame so all that can take effect properly
  wait()
end

local function badeline_vanishes()
  -- tell the badeline entity to disappear
  badeline:Vanish()
  Input.Rumble(getEnum("Celeste.RumbleStrength", "Medium"), getEnum("Celeste.RumbleLength", "Medium"))
  -- clear the stored variable so the memory can be used for something else
  badeline = nil

  -- wait until the next frame
  wait()
end

function onBegin(room)
  disableMovement()
  badeline_appears()
  coroutine.yield(getLevel():ZoomTo(vector2(140, 105), 1.2, 4))
  say("solarisLuaEnding1")
  player.ForceCameraUpdate = false
  getLevel():add(coroutineEntity)
  playSound("event:/game/06_reflection/badeline_freakout_2", player.Position)
  coroutineEntity:add(monocle.Coroutine(badeline:FloatTo(vector2(29540, -6619), -1, false)))
  coroutineEntity:add(monocle.Coroutine(walk(20, false, 2)))
  coroutine.yield(getLevel():ZoomAcross(vector2(170, 110), 1.5, 0.5))
  say("solarisLuaEnding2")
  playSound("event:/game/06_reflection/badeline_freakout_3", player.Position)
  coroutineEntity:add(monocle.Coroutine(badeline:FloatTo(vector2(29590, -6619), -1, false)))
  coroutineEntity:add(monocle.Coroutine(walk(30, false, 3)))
  coroutine.yield(getLevel():ZoomAcross(vector2(210, 120), 2, 0.35))
  say("solarisLuaEnding3")
  playSound("event:/game/06_reflection/badeline_freakout_4", player.Position)
  coroutineEntity:add(monocle.Coroutine(badeline:FloatTo(vector2(29640, -6619), -1, false)))
  coroutineEntity:add(monocle.Coroutine(walk(40, false, 4)))
  coroutine.yield(getLevel():ZoomAcross(vector2(250, 130), 2.5, 0.2))
  say("solarisLuaEnding4")
  badeline_vanishes()
  coroutineEntity:add(monocle.Coroutine(coroutine.yield(engine.Scene:ZoomBack(4))))
  coroutineEntity:add(monocle.Coroutine(walk(200, false, 1)))
  getLevel():ResetZoom()
end

function onEnd(room, wasSkipped)
  if badeline then
    badeline:RemoveSelf()
    badeline = nil
  end
  getLevel():ResetZoom()
  enableMovement()
end