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

pHPPercentDmg = GetFloatParam("damage", "0.25")

local min, max = math.min, math.max

function init()
    shape = FindShape("explosive")
    if shape == 0 then
        disabled = true
        cEntity:EnqueueDeletion()
    else
        MI, MA = GetShapeBounds(shape)
        SIZE = VecSub(MA, MI)
        EXTENT = tonumber(GetTagValue(shape, "explosive")) * 1.5
        disabled = false
    end
end

function update(dt)
    if disabled then return end

    if not IsShapeBroken(shape) then return end

    local tr = GetShapeWorldTransform(shape)
    local mi, ma = TransformToParentPoint(tr, VecScale(SIZE, -EXTENT)), TransformToParentPoint(tr, VecScale(SIZE, EXTENT))
    mi[1],mi[2],mi[3], ma[1],ma[2],ma[3] = min(mi[1],ma[1]),min(mi[2],ma[2]),min(mi[3],ma[3]), max(mi[1],ma[1]),max(mi[2],ma[2]),max(mi[3],ma[3])

    QueryRequire('physical dynamic')
    local list = QueryAabbBodies(mi, ma)
    local seen = {}
    for i = 1, #list do
        local body = list[i]
        local veh = GetBodyVehicle(body)
        if veh > 0 and HasTag(veh, "customhealth") and not seen[veh] and GetVehicleHealth(veh) > 0 then
            TriggerEvent(EVENTS.UPDATE_HEALTH, veh .. ";" .. pHPPercentDmg)
            seen[veh] = true
        end
    end
    disabled = cEntity:EnqueueDeletion()
end
