local calc = require("#monocle.calc")
local lua_helper = celeste.Mod.LuaCutscenes.LuaHelper
local ring = {}
local scene = getRoom()
local finishedRoutine = false
local lockPos = player.Center

local function damageRoutine()
    if player.DashAttacking then
        return
    end

    die()
end

local function makeCoroutine(func)
  return monocle.Coroutine(lua_helper.LuaCoroutineToIEnumerator(coroutine.create(func)))
end

local function makeSpikeRoutine(entity, dir)
    return function ()
        entity.Speed = vector2(calc.AngleToVector(calc.Circle * dir / 5, 50).X, -300)
        wait(10)
        entity:removeSelf()
    end
end

local function makeDartRoutine(entity, dir)
    return function()

        local maxSpeed = calc.AngleToVector(calc.Circle * dir / 6, 75) + randVector(32)

        entity.Speed = maxSpeed
        local lifetime = 1

        while lifetime > 0 do
            
            entity.Speed = maxSpeed * (lifetime / 1)


            lifetime = lifetime - engine.deltaTime

            wait(0)

        end

        local spikes = {}

        for i = 1, 5, 1 do

            spikes[#spikes+1] = getNewBasicAttackActor(entity.Center, getCircle(4), "badeline_projectile", 0.5, 200, true, false, damageRoutine, 0.5, 0.5)
            
            spikes[#spikes]:add(makeCoroutine(makeSpikeRoutine(spikes[#spikes], i)))

            scene:add(spikes[#spikes])
        end

        entity:removeSelf()
    end
end




function onBegin()

    positionTween(player.Position + calc.AngleToVector(calc.NextFloat(calc.Random, -calc.Circle / 2), 128), 0.1)
    
    setFlag("pauseIdle", true)

    wait(0.2)

    setFlag("pauseIdle", false)

    for i = 1, 6, 1 do

        ring[#ring+1] = getNewBasicAttackActor(puppet.Center, getCircle(4), "badeline_projectile", 0.5, 200, true, false, damageRoutine)
        
        ring[#ring]:add(makeCoroutine(makeDartRoutine(ring[#ring], i)))

        scene:add(ring[#ring])
    end

    wait(2)

    
end

function getXSpeed()
    return sign(-(puppet.Position.X - lockPos.X)) * 150
end

function getYSpeed()
    return sign((puppet.Position.X - lockPos.X + 16)) * 150
end

function sign(x)
    return (x<0 and -1) or 1
end  

function abs(x)
    return x * sign(x)
end

function randVector(max)
    return vector2(calc.NextFloat(calc.Random, max), calc.NextFloat(calc.Random, max))
end