#include "../../config/events.lua"
#include "../../script/helpers/entity.lua"
#include "../../script/helpers/mathfr.lua"

rollers = nil
body = nil
snd = nil
vol = nil
pos = nil
delay = 0
disabled = nil

function init()
    rollers     = FindJoints("roller")
    body        = FindBody()
    snd         = LoadLoop("MOD/snd/grinder.ogg")
    vol         = 1.0
    local sound_loc = FindLocation("sound_pos")
    pos         = sound_loc > 0 and GetLocationTransform(sound_loc).pos
    max_dmg     = 0.1
    Delete(sound_loc)
end

function tick(dt)
    if disabled then return end

    for i=#rollers, 1, -1 do repeat
        local hinge = rollers[i]
        if IsJointBroken(hinge) then
            table.remove(rollers, i)
            if #rollers == 0 then
                disabled = cEntity:EnqueueDeletion()
            end
            break
        end
        SetJointMotor(hinge, 3.0)
    until true end

    PlayLoop(snd, pos, vol)
end

function update(dt)
    if disabled then return end
    if delay > dt then delay = delay - dt return end

    WatchBodyHit(body)
    if not IsBodyHitted(body) then return end

    local seen = {}
    for index = 0, GetBodyHitsCount(body) - 1 do
        local other_body, impulse, pos, normal, this_vel, other_vel = GetBodyHit(body, index)
        local veh = GetBodyVehicle(other_body)
        impulse = math.abs(impulse)
        if veh > 0 and HasTag(veh, "customhealth") and impulse >= 125 and not seen[veh] and GetVehicleHealth(veh) > 0 then
            local dmg = math:MapRangeClamped(math.sqrt(impulse), 15, 150, 0, max_dmg)
            if dmg > 0 then
                TriggerEvent(EVENTS.UPDATE_HEALTH, veh .. ";" .. dmg)
                seen[veh] = true
            end
        end
    end
    delay = 1
end
