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

pVelocityMin = GetFloatParam("velocity_min", 1)
pVelocityMax = GetFloatParam("velocity_max", 1)
pInvertVelChance = GetFloatParam("velocity_neg_chance", 0.0)

function init()
    shapes = FindShapes("part")
    shapes_vc = {}
    for i = 1, #shapes do
        shapes_vc[i] = GetShapeVoxelCount(shapes[i])
    end
    j = FindJoint("roll")
    if pVelocityMin ~= pVelocityMax then
        pVelocity = math.random(pVelocityMin*10, pVelocityMax*10)/10
    else
        pVelocity = pVelocityMin
    end
    if pInvertVelChance ~= 0 and math.random() < pInvertVelChance then
        pVelocity = -pVelocity
    end
end

function tick(dt)
    if disabled then return end
    if #GetJointShapes(j) ~= 2 then
        disabled = cEntity:EnqueueDeletion()
        SetJointMotor(j, pVelocity * 0.5, 100)
        return
    end
    local broken = false
    local wb
    for i = 1, #shapes do
        local shape = shapes[i]
        wb = wb or GetWorldBody()
        if not broken and GetShapeVoxelCount(shape) / shapes_vc[i] <= 0.95 then
            broken = true
        end
        if broken and GetShapeBody(shape) ~= wb then
            disabled = cEntity:EnqueueDeletion()
            SetJointMotor(j, pVelocity * 0.5, 100)
            return
        end
    end
    SetJointMotor(j, pVelocity)
end
