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

pIntegrityForFail = GetFloatParam("integrity_for_fail", 0.8) -- target counts as failed below this voxelcount threshold

function init()
    shapes = FindShapes()
    voxcount = 0
    local positions = {}
    for i = 1, #shapes do
        local shape = shapes[i]
        voxcount = voxcount + GetShapeVoxelCount(shape)
        positions[i] = GetShapeWorldTransform(shape).pos
    end
    center = math:VecMidPoint(unpack(positions))
    disabled = false
    target = cEntity:FindClosestBodyToPos(center, "target", true)
end

function update(dt)
    if disabled then return end

    local new_voxcount = 0
    for i = 1, #shapes do
        new_voxcount = new_voxcount + GetShapeVoxelCount(shapes[i])
    end

    local result = new_voxcount / voxcount
    if result <= pIntegrityForFail then
        SetTag(target, "target", "disabled")
        SetTag(target, "failed")
        SetInt("level.failed", GetInt("level.failed")+1)
        SetString("hud.hintinfo", GetTranslatedStringByKey("TARGET_FAILED"))
        disabled = cEntity:EnqueueDeletion()
    end
end
