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

function onBegin()
  local knightNum = tonumber(string.sub(bossID, -1))
  local changeFlag = "change_watcher_" .. knightNum
  local turnFlag = "turn_" .. knightNum

  setFlag(turnFlag, true)
  while getFlag(turnFlag) do --wait for Knight to try to find the player to face them
    wait()
  end

  setYSpeed(-200)
  wait(0.1) --wait until jump apex
  playPuppetAnim("rollstart")
  AttackSfx = celeste.SoundSource()
  addComponentToBoss(AttackSfx:Play("event:/CC/CC_HollowKnight/SFX/Boss SFX/WatcherKnightAirLoop"))
  --AttackSfx = Audio.Play("event:/CC/CC_HollowKnight/SFX/Boss SFX/WatcherKnightAirLoop", puppet.Position)
  setFlag(changeFlag, true)
  while not puppet.Grounded do
    wait()
  end
  local dist = player.Position.X - puppet.Position.X
  if dist > 250 then
    dist = 250
  elseif dist < -250 then
    dist = -250
  end
  setYSpeed(-500) --jump
  setXSpeed(dist * 1.5) --dist/fly timer

  local oldSpeed = puppet.Speed.X
  while not puppet.Grounded do
    wait()
    local newSpeed = puppet.Speed.X
    if newSpeed == 0 then
      dist = dist * -1
      setXSpeed(-oldSpeed)
    end
  end

	playSound("event:/CC/CC_HollowKnight/SFX/Boss SFX/LandSound",puppet.Position)
  setXSpeed(dist/1.8)
  setYSpeed(-350)

  oldSpeed = puppet.Speed.X
  while not puppet.Grounded do
    wait()
    local newSpeed = puppet.Speed.X
    if newSpeed == 0 then
      setXSpeed(-oldSpeed)
    end
  end
  
  speedXTweenTo(0, 0.25)
  AttackSfx:Stop()
  --Audio.Stop(AttackSfx, false)
  playSound("event:/CC/CC_HollowKnight/SFX/Boss SFX/LandSound",puppet.Position)
  playPuppetAnim("idle")
  setFlag(changeFlag, true)

  setFlag(turnFlag, true)
  while getFlag(turnFlag) do --wait for Knight to try to find the player to face them
    wait()
  end
  wait(0.25)
  --return to normal
end