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(entity)
    return function()
        
        wait(1)

        local lifetime = 5
        local target = calc.Toward(entity.Position, player.Center, 1)

        local t = 1.5

        while lifetime > 0 do
            
            entity.Position = entity.Position + target * t
            
            t = t + 0.1

            lifetime = lifetime - engine.deltaTime

            wait(0)
        end

        entity:RemoveSelf()
        finishedRoutine = true
    end
end



function onBegin()
    
    setFlag("pauseIdle", true)

    local currPos = puppet.Position

    log("test4")

    local pos = player.Position + calc.AngleToVector(calc.NextFloat(calc.Random, calc.Circle), 128)

    

    positionTween(pos, 0.1)

    for i = 1, 3, 1 do
        ring[#ring+1] = getNewBasicAttackEntity(currPos * (i/3) + pos * ((3-i)/3), getCircle(4), "badeline_projectile", true, damageRoutine)
        
        ring[#ring]:add(makeCoroutine(makeDartRoutine(ring[#ring])))
        
        

        scene:add(ring[#ring])
    end

    setFlag("pauseIdle", false)

    wait(0.5)

    setFlag("pauseIdle", true)

    local currPos = puppet.Position

    log("test4")

    local pos = player.Position + calc.AngleToVector(calc.NextFloat(calc.Random, calc.Circle), 128)

    

    positionTween(pos, 0.1)

    for i = 1, 3, 1 do
        ring[#ring+1] = getNewBasicAttackEntity(currPos * (i/3) + pos * ((3-i)/3), getCircle(4), "badeline_projectile", true, damageRoutine)
        
        ring[#ring]:add(makeCoroutine(makeDartRoutine(ring[#ring])))
        
        

        scene:add(ring[#ring])
    end

    setFlag("pauseIdle", false)

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