#include "../helpers/utils.lua"
#include "../helpers/particles.lua"
#include "../helpers/timer.lua"

local MIN_EXPLODE_TIME = 1.5
local MAX_EXPLODE_TIME = 10.5

function init()
    locs = map(FindLocations("distant_firework", true), function(a) local pos=GetLocationTransform(a).pos; Delete(a); return {pos, nextRandTime(), 0} end)
end

function update(dt)
    timer_manager:Tick(dt)

    for i = 1, #locs do
        local pos, next_time, time = unpack(locs[i])
        if time >= next_time then
            locs[i][2] = nextRandTime()
            locs[i][3] = 0
            local r, g, b = unpack(randColor())
            local lifetime = cParticles:Firework{
                num=math.random(35, 100),
                pos=pos,
                r=r,
                g=g,
                b=b,
                minSize=.3,
                maxSize=.75,
                maxVel=35,
                lifeMax=9,
                gravity=-6,
                ret_lifetime=true
            }
            timer_manager:CreateTimer("firework_"..i, 0, true, function(data)
                local life, time, i, pos, r, g, b = unpack(data)
                if GetTime()-time >= life then
                    timer_manager:ClearTimer("firework_"..i)
                else
                    for _=1, 5 do
                        PointLight(VecAdd(utils:rndVec(math.random(2, 7), true), pos), r, g, b, math.random(85, 100)/100*65)
                    end
                    data[4] = VecSub(pos, {0, 0.1})
                end
            end, {lifetime, GetTime(), i, pos, r, g, b})
        else
            locs[i][3] = time+dt
        end
    end
end

function randColor()
    local t = {
        {1, utils:rnd(.3,.5), utils:rnd(.3,.5)},
        {utils:rnd(.3,.5), 1, utils:rnd(.3,.5)},
        {utils:rnd(.3,.5), utils:rnd(.3,.5), 1},
        {1, 1, utils:rnd(.8,1)}
    }
    return t[math.random(#t)]
end

function nextRandTime()
    return math.random(MIN_EXPLODE_TIME*10, MAX_EXPLODE_TIME*10)/10
end
