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 makeDartRoutine(angle, entity)
    return function()
        local t = angle
        local lifetime = 2

        while lifetime > 0 do
            entity.Position = puppet.Center + calc.AngleToVector(t,32)
            
            if lifetime > 0.5 then
                t = t + 0.05
            else
                t = t + lifetime / 10
            end
            lifetime = lifetime - engine.deltaTime
            wait(0)
        end

        lifetime = 1
        local mult = 1

        while lifetime > 0 do
            entity.Position = entity.Position + calc.AngleToVector(t,4) * mult
            mult = mult + 0.01
            lifetime = lifetime - engine.deltaTime
            wait(0)
        end

        entity:RemoveSelf()
        finishedRoutine = true
    end
end



function onBegin()

    finishedRoutine = false

    
    local angleOffset = calc.NextFloat(calc.Random, calc.Circle)
    
    for i = 1, 15, 1 do
        local vec = calc.AngleToVector(calc.Circle * i / 15 + angleOffset, 32)
        ring[#ring+1] = getNewBasicAttackEntity(puppet.Center + vec + vector2(0, -12), getCircle(4), "badeline_projectile", true, damageRoutine)
        
        ring[#ring]:add(makeCoroutine(makeDartRoutine(calc.Circle * i / 15, ring[#ring])))
        
        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