#include "../../script/helpers/entity.lua"

function init()
    shape               = FindShape()
    body                = GetShapeBody(shape)
    WATER_LEAK_TIMER    = 0
    WATER_LEAK_MAX      = 1
    completed           = false
end

function update(dt)
    if completed then return end

    if IsBodyBroken(body) then
        if WATER_LEAK_TIMER < WATER_LEAK_MAX then
			WATER_LEAK_TIMER = WATER_LEAK_TIMER + dt
            SpawnWaterParticle()
        elseif not completed then
            completed = true
        end
    end
end

local function rdm(min, max)
    return math.random(min or 0, max or 1)
end

local function VecRdm(min, max)
    return Vec(rdm(min, max),rdm(min, max),rdm(min, max))
end

function SpawnWaterParticle()
    pos             = GetBodyTransform(body).pos 
    local emitPos   = pos
    local q         = 1.0 - WATER_LEAK_TIMER / WATER_LEAK_MAX
    local v         = q * 10.0 + 2.0
    local r         = q * 0.4 + 0.1
    local pc        = math.ceil(q * 5) + 3

    ParticleType("plain")
    ParticleTile(1)
    ParticleColor(0.9, 0.95, 1.0)
    ParticleAlpha(1.0, 0.0)
    ParticleGravity(-15, -5, "easeout")
    ParticleStretch(q * 10, 0)
    ParticleCollide(0, 1, "constant", 0.2, 0.1)
    ParticleSticky(0.25)

    for i = 1, pc do
        ParticleRadius(r, r * 3)
        local vel = VecScale(Vec(rdm(-0.25, 0.25), -1, rdm(-0.25, 0.25)), rdm(0.4, 0.7) * v)
        local pos = VecAdd(emitPos, VecRdm(-1.75, 1.75))
        SpawnParticle(pos, vel, q + rdm(2.0, 6.0))
    end
end