-- 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 cjson = require 'cjson'
local log = require 'mc.logging'

local COMPONENT_TYPE_FAN<const> = 4

local m = {}

local severity = {
    [0] = 'Informational',
    [1] = 'Minor',
    [2] = 'Major',
    [3] = 'Critical'
}

function m.get_severity_by_code(health_code)
    if not severity[health_code] then
        return cjson.null
    end

    return severity[health_code]
end

local health = {
    [0] = 'OK',
    [1] = 'Warning',
    [2] = 'Warning',
    [3] = 'Critical'
}

function m.get_health_by_code(health_code)
    if not health[health_code] then
        return cjson.null
    end

    return health[health_code]
end

function m.get_fan_state(fan_info)
    if fan_info.IsTwins then
        if fan_info.RearPresence == 0 and fan_info.FrontPresence == 0 then
            return "Absent"
        elseif fan_info.FrontSpeed == 0 and fan_info.RearSpeed == 0 then
            return "StandbyOffline"
        else
            return "Enabled"
        end
    else
        if fan_info.RearPresence == 0 then
            return "Absent"
        elseif fan_info.RearSpeed == 0 then
            return "StandbyOffline"
        else
            return "Enabled"
        end
    end
end

function m.get_fan_status(components, fan_info, fan_id)
    local state = m.get_fan_state(fan_info)
    local status = 0
    if state ~= "Absent" then
        for _, item in pairs(components) do
            -- 查看对应风扇组件的健康状态
            if item.Type == COMPONENT_TYPE_FAN and item.Presence == 1 and item.Health > status and
                item.Name == "Fan" .. fan_id then
                status = item.Health
            end
        end
    end
    local status_obj = cjson.json_object_new_object()
    status_obj[1] = state
    status_obj[2]= state == "Absent" and cjson.null or m.get_health_by_code(status)
    status_obj[3] = state == "Absent" and cjson.null or m.get_severity_by_code(status)
    return status_obj
end

function m.is_valid_fan_id(input)
    if input[1] == '' then
        return false
    end
    local obj = mdb.get_object(bus, input[1], 'bmc.kepler.Systems.Fan')
    if not obj or input[2] ~= tostring(obj.FanId) then
        return false
    end
    return true
end

return m
