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

  setFlag(changeFlag, true)
  playPuppetAnim("rollstart")
  AttackSfx = celeste.SoundSource()
  addComponentToBoss(AttackSfx:Play("event:/CC/CC_HollowKnight/SFX/Boss SFX/WatcherKnightGroundLoop"))
  --AttackSfx = Audio.Play("event:/CC/CC_HollowKnight/SFX/Boss SFX/WatcherKnightGroundLoop", puppet.position)
  local spinSpeed = 200 * puppet.Facing
  wait(setXSpeedDuring(-spinSpeed / 2, 0.37))
  setXSpeed(spinSpeed)
  local timer = 0
  local dist = math.abs(player.Position.X - puppet.Position.X)
  while puppet.Speed.X ~= 0 and timer < 2 do
    timer = timer + monocle.Engine.DeltaTime
    wait()
    local newDist = math.abs(player.Position.X - puppet.Position.X)
    if newDist > dist and newDist > 150 then
      break
    end
    dist = newDist
  end
  --wait until it stops near a wall
  setFlag(changeFlag, true)
  AttackSfx:Stop()
  --Audio.Stop(AttackSfx, false)
  playPuppetAnim("idle")
  speedXTween(spinSpeed * (puppet.Speed.X == 0 and -1 or 1), 0, 0.25)
  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