DiseaseCareUtil = {}
DiseaseCareUtil.COOLDOWN_MS = 500

local function getWorkAreaStats(spec)
    local params = spec and spec.workAreaParameters or nil
    if params == nil then
        return 0, 0
    end

    local changedArea = params.lastStatsArea or params.lastChangedArea or params.lastArea or 0
    local totalArea = params.lastTotalArea or changedArea or 0

    return changedArea, totalArea
end

local function getCurrentMissionTime()
    return g_currentMission and g_currentMission.time or 0
end

function DiseaseCareUtil.handleCareAction(tool, action, spec, fallbackWorked)
    if g_server == nil or DiseaseCore == nil or tool == nil or action == nil then
        return
    end

    local changedArea, totalArea = getWorkAreaStats(spec)
    local didWork = (changedArea or 0) > 0 or fallbackWorked == true
    if not didWork then
        return
    end

    tool.spec_diseaseCareUtil = tool.spec_diseaseCareUtil or { lastRunByAction = {} }
    local state = tool.spec_diseaseCareUtil
    local now = getCurrentMissionTime()
    local lastRun = state.lastRunByAction[action] or 0
    if now - lastRun < DiseaseCareUtil.COOLDOWN_MS then
        return
    end

    state.lastRunByAction[action] = now
    DiseaseCore:onCareActionAt(tool, action, changedArea or 0, totalArea or 0)
end

