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()
  log("0")
  -- tell the badeline entity to disappear
  badeline:Vanish()
  log("1")
  -- clear the stored variable so the memory can be used for something else
  log("2")
  badeline = nil

  -- wait until the next frame
  log("3")
  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()
  coroutine.yield(engine.Scene:ZoomBack(4))
  player.ForceCameraUpdate = true
  wait(1)
  walk(525, false, 0.8)
  walk(25, false, 0.5)
  walk(15, false, 0.2)
  wait(1)
  coroutine.yield(getLevel():ZoomAcross(vector2(160, 130), 0.3, 7))
  wait(2)
  player.DummyAutoAnimate = false
  player.Sprite:Play("sitDown", false)
  wait(7)
  engine.Scene:NextColorGrade("fadeBlackLunar", 2) 
  wait(2)
  completeArea(True, False, True)
end

function onEnd(room, wasSkipped)
  if badeline then
    badeline:RemoveSelf()
    badeline = nil
  end
  player.ForceCameraUpdate = true
  getLevel():ResetZoom()
  enableMovement()
  completeArea(True, False, True)
end