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 + 32
    scale = -1
  else
    pos_x = player.Position.X + 32
    scale = -1
  end
  local pos_y = player.Position.Y - 12

  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_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 onTalk()
	local level = getLevel()
	level:add(coroutineEntity)
	local extraDialogA = getFlag("scene3")
	local extraDialogB = getFlag("scene9")
	disableMovement()
	makeUnskippable()
	setFlag("scene12", true)
	walkTo(20712)
	walk(8)
	badeline_appears()
	coroutineEntity:add(monocle.Coroutine(level:ZoomTo(vector2(180,90), 1.35, 3)))
	player.DummyAutoAnimate = false
	player.Sprite:Play("sitDown")
	say("LL_EXTRA_L_1")
	wait(0.5)
	if extraDialogA then
	  say("LL_EXTRA_L_EXTRA_1")
	end
	say("LL_EXTRA_L_2")
	wait(0.5)
	if extraDialogB then
	  say("LL_EXTRA_L_EXTRA_2")
	end
	wait(1.0)
	say("LL_EXTRA_L_3")
	coroutineEntity:add(monocle.Coroutine(level:ZoomBack(2.5)))
	player.Sprite:Play("wakeUp")
	wait(2.5)
	player.DummyAutoAnimate = true
	badeline:Vanish()
	wait()
end

function onEnd(room, wasSkipped)
	if wasSkipped then
	setFlag("scene12", true)
	enableMovement()
	badeline:Vanish()
	else
	setFlag("scene12", true)
	enableMovement()
	end
end