#include "helpers/entity.lua"

THRESHERVELOCITY = nil
thisVehicle = nil
v_b = nil
thresherJoints = nil
thresher_shape = nil
thresher_body = nil
shape_voxel_cnt = nil
snd = nil
vol = nil
disabled = nil
joint_strength = nil
active = nil

function init()
    -- Config
    THRESHERVELOCITY = 4.0

    thisVehicle     = FindVehicle()
    v_b             = GetVehicleBody(thisVehicle)
    thresherJoints  = FindJoints("thresher")
    thresher_shape  = FindShape("thresher")
    thresher_body   = GetShapeBody(thresher_shape)
    shape_voxel_cnt = GetShapeVoxelCount(thresher_shape)
    snd             = LoadLoop("MOD/snd/blades.ogg")
    vol             = 0.5
    disabled        = false
    local b_m = GetBodyMass(v_b)
    joint_strength = b_m * 0.8
end

function update(dt)
    if disabled then return end
    if GetVehicleHealth(thisVehicle) <= 0 or GetShapeVoxelCount(thresher_shape) < shape_voxel_cnt*0.5 then
        disabled = cEntity:EnqueueDeletion()
    end
    local jointed = GetJointedBodies(v_b)
    local found = false
    for i = 1, #jointed do
        local body = jointed[i]
        if body == thresher_body then
            found = true
            break
        end
    end
    if not found then
        disabled = cEntity:EnqueueDeletion()
    end

    active = not disabled and HasTag(thresher_body, "autobreak")

    for i=1, #thresherJoints do
        local joint = thresherJoints[i]
        local vel = active and THRESHERVELOCITY or 0
        SetJointMotor(joint, vel, joint_strength)
    end
end

function tick(dt)
    if disabled then return end
    if not active then return end

    PlayLoop(snd, GetShapeWorldTransform(thresher_shape).pos, vol)
end
