local monocle = require("#monocle")
local coroutineEntity = monocle.Entity()

local function badeline_appears(left_side)
  local pos_x, scale
  if left_side then
    pos_x = player.Position.X - 64
    scale = -1
  else
    pos_x = player.Position.X + 64
    scale = 1
  end
  local pos_y = player.Position.Y - 8

  badeline = celeste.BadelineDummy(vector2(pos_x, pos_y))
  badeline.Sprite.Scale = vector2(scale, 1.0)
  getLevel():Add(badeline)

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

  wait()
end

local function badeline_vanishes()
  getLevel().Displacement:AddBurst(badeline.Center, 0.5, 8, 32, 0.5)
  getLevel():Remove(badeline)

  wait()
end

local function badeline_moves(pos_x, scale, pos_y)
  getLevel().Displacement:AddBurst(badeline.Center, 0.5, 8, 32, 0.5)
  getLevel():Remove(badeline)

  badeline = celeste.BadelineDummy(vector2(pos_x, pos_y))
  badeline.Sprite.Scale = vector2(scale, 1.0)
  getLevel():Add(badeline)

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

  wait()
end

function onBegin()
	local level = getLevel()
	level:add(coroutineEntity)
	disableMovement()
	coroutineEntity:add(monocle.Coroutine(level:ZoomTo(vector2(180,100), 1.35, 3)))
	coroutineEntity:add(monocle.Coroutine(run(156)))
	badeline_appears()
	say("LL_CUTSCENE_D_1")
	badeline_moves(player.Position.X + 18, -1, player.Position.Y - 8)
	say("LL_CUTSCENE_D_2")
	walk(-16)
	say("LL_CUTSCENE_D_3")
	player.DummyAutoAnimate = false
	player.Sprite:Play("sitDown")
	coroutineEntity:add(monocle.Coroutine(level:ZoomAcross(vector2(210,100), 1.5, 2)))
	coroutineEntity:add(monocle.Coroutine(wait(0.2)))
	badeline_moves(player.Position.X + 72, 1, player.Position.Y - 8)
	wait(2.0)
	say("LL_CUTSCENE_D_4")
	badeline_vanishes()
	coroutineEntity:add(monocle.Coroutine(level:ZoomAcross(vector2(180,100), 1.35, 2)))
	coroutineEntity:add(monocle.Coroutine(wait(0.2)))
	say("LL_CUTSCENE_D_5")
	player.Sprite:Play("wakeUp")
	coroutineEntity:add(monocle.Coroutine(level:ZoomAcross(vector2(200,100), 1.35, 3)))
	coroutineEntity:add(monocle.Coroutine(wait(2.5)))
	player.DummyAutoAnimate = true
	walk(16)
	say("LL_CUTSCENE_D_6")
	wait(1.5)
	coroutineEntity:add(monocle.Coroutine(level:ZoomBack(1.5)))
	say("LL_CUTSCENE_D_7")
	level:ResetZoom()
end

function onEnd(room, wasSkipped)
	if wasSkipped then
	enableMovement()
	badeline_vanishes()
	level:ResetZoom()
	else
	enableMovement()
	level:ResetZoom()
	end
end