-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
--
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.
local JOBS_PATH = "/bmc/kepler/JobService/Jobs"
local JOB_INTERFACE = "bmc.kepler.JobService.Job"
local OK = "OK"
local WARNING = "Warning"
local CRITICAL = "Critical"

local m = {}

local function is_common_user(privileges)
    for _, value in ipairs(privileges) do
        if value ~= 'ReadOnly' and value ~= 'ConfigureSelf' then
            return false
        end
    end

    return true
end

function m.get_job_members(privileges)
    local res = {
        ['Count'] = 0,
        ['Members'] = {}
    }

    -- job任务信息不允许低权限用户查询，只有拥有非ReadOnly和ConfigureSelf权限的用户可以查询
    if is_common_user(privileges) then
        return res
    end

    local jobs = mdb.get_sub_objects(bus, JOBS_PATH, JOB_INTERFACE)
    if not jobs or next(jobs) == nil then
        return res
    end
    for _, obj in pairs(jobs) do
        if obj.Origin == 'Redfish' then
            local t ={}
            t['@odata.id'] = "/redfish/v1/JobService/Jobs/" .. obj.Id
            res.Members[#res.Members+1] = t
            res.Count = res.Count + 1
        end
    end

    return res
end

function m.get_health_rollup()
    local jobs = mdb.get_sub_objects(bus, JOBS_PATH, JOB_INTERFACE)
    if not jobs then
        return OK
    end
    for _, obj in pairs(jobs) do
        if obj.Origin == 'Redfish' and obj.JobStatus == CRITICAL then
            return WARNING
        end
    end

    return OK
end

function m.check_update_params(data)
    return data and #data ~= 0
end

return m
