-- 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 file_sec = require('utils.file')
local cjson = require('cjson')
local m = {}
local FAN_INTERFACE <const> = 'bmc.kepler.Systems.Fan'
local COOLING_FAN_INTERFACE <const> = 'bmc.kepler.Systems.CoolingFan'

-- 从文件获取bios全打印开关的状态
-- ","SYSDBGLevel":"result","
function m.get_bios_print_state()
    local path = '/data/opt/currentvalue.json'
    local fp = file_sec.open_s(path, 'r')
    if not fp then
        return { false }
    end
    local buf = fp:read('a')
    fp:close()
    local _, pos = string.find(buf, '"SYSDBGLevel":')
    if pos then
        local _, next_pos = string.find(buf, '"', pos + 1)
        local _, end_pos = string.find(buf, '"', next_pos + 1)
        if end_pos then
            local result = string.sub(buf, next_pos + 1, end_pos - 1)
            return { true, result }
        else
            return { false }
        end
    else
        return { false }
    end
end

function m.check_privilege(user_privilege, target_privilege)
    for _, v in ipairs(user_privilege) do
        if v == target_privilege then
            return true
        end
    end

    error(base_messages.InsufficientPrivilege())
end

function m.get_cooling_fan_list(input)
    local table_input = cjson.json_object_to_table(input)
    local cooling_fan_objs = cjson.json_object_new_array()

    for _, path in pairs(table_input) do
        local temp_obj = mdb.get_object(bus, path, COOLING_FAN_INTERFACE)
        local cooling_fan_obj = cjson.json_object_new_object()
        cooling_fan_obj['FanId'] = temp_obj.FanId
        cooling_fan_obj['Level'] = temp_obj.Level
        cooling_fan_obj['FrontPresence'] = temp_obj.FrontPresence
        cooling_fan_obj['RearPresence'] = temp_obj.RearPresence
        cooling_fan_objs[#cooling_fan_objs + 1] = cooling_fan_obj
    end

    return cooling_fan_objs
end

function m.get_thermal_fan_list(input)
    local table_input = cjson.json_object_to_table(input)
    local fan_objs = cjson.json_object_new_array()

    for _, path in pairs(table_input) do
        local temp_obj = mdb.get_object(bus, path, FAN_INTERFACE)
        local fan_obj = cjson.json_object_new_object()
        fan_obj['IsTwins'] = temp_obj.IsTwins
        fan_objs[#fan_objs + 1] = fan_obj
    end

    return fan_objs
end

return m