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

disabled = nil
duration = 5

function init()
    basis               = FindShape("basis")
    body                = GetShapeBody(basis)
    voxelsToBreakCrane  = 2950
    isBroken            = false
end

function update(dt)
    if disabled then return end

    if not IsBodyBroken(body) then return end
    if not isBroken then
        if GetShapeVoxelCount(basis) < voxelsToBreakCrane then
            isBroken = true
            TriggerEvent(EVENTS.VEHICLE_ACTIVATED_TRAP, 'crane')
        else
            return
        end
    end

    duration = duration - dt
    if duration < 0 then disabled = cEntity:EnqueueDeletion() 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 >= 50 and not seen[veh] and GetVehicleHealth(veh) > 0 then
            local dmg = math:MapRangeClamped(math.sqrt(impulse), 12, 50, 0, 0.1)
            if dmg > 0 then
                TriggerEvent(EVENTS.UPDATE_HEALTH, veh .. ";" .. dmg)
                seen[veh] = true
            end
        end
    end
end
