local function createNailCollider(func, collider)
  return celeste.Mod.CrossoverCollab.CrossoverCollabModule.CreateNailColliderDelegate(func, collider)
end

local function getPlayerCollider(func, collider)
  return celeste.Mod.CrossoverCollab.CrossoverCollabModule.CreatePlayerCollider(func, collider)
end

local function killSwing(player)
  addConstantBackgroundCoroutine(function ()
    --log("wait for parry")
    wait()
    --log("kill")
    die(normalize(player.Position - puppet.Position))
  end)
end

local function parry()
  if puppet.BossHitCooldown <= 0 then
    --log("parry")
    giveInvincibleFrames(0.25)
    celeste.Mod.Kelper.Mechanics.Nail.NailRebound(0.5)
    player:Play("event:/CC/CC_HollowKnight/SFX/Boss SFX/Parry")
    resetHitCooldown()
  end
  return true
end

local function makeSwing(collider)
  local swing = getNewBasicAttackEntity(puppet.Position, collider, "", true)
  local origKill = getComponentFromEntity(swing, "PlayerCollider")
  if origKill then
    origKill:RemoveSelf()
  end
  local parryCollider = createNailCollider(parry, swing.Collider)
  local killCollider = getPlayerCollider(killSwing, swing.Collider)

  swing:Add(parryCollider)
  swing:Add(killCollider)
  swing:Add(getEntityTimer(0.05))

  return swing
end

function onBegin()
  local knightNum = tonumber(string.sub(bossID, -1))
  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

  if v2L(player.Position - puppet.Position) > 100 then
    playPuppetAnim("walk")
    wait(setXSpeedDuring(50 * puppet.Facing, 1))
    wait(speedXTweenTo(0, 0.1))
    playPuppetAnim("idle")
    return
  end

  local facingLeft = puppet.Facing < 0

  local colliderList = getColliderList(getHitbox(60, 35, facingLeft and -60 or 0, -20),
    getHitbox(20, 20, facingLeft and 0 or -20, -20))

  local firstSwing = makeSwing(colliderList)

  playPuppetAnim("slashA")
  playSound("event:/CC/CC_HollowKnight/SFX/Boss SFX/SwordRandomized",puppet.Center)
  wait(0.5)
  addEntity(firstSwing)
  wait(0.1)

  local secondSwing = makeSwing(getHitbox(30, 45, facingLeft and -50 or 20, -30))

  playPuppetAnim("slashB")
  playSound("event:/CC/CC_HollowKnight/SFX/Boss SFX/SwordRandomized",puppet.Center)
  wait(0.2)
  addEntity(secondSwing)
  wait(0.1)

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