-- Copyright (c) 2025 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 m = {}

local FANGROUP_MDB_INTF <const> = 'bmc.kepler.Chassis.FanGroup'
local FANGROUP_MDB_PATH <const> = '/bmc/kepler/Chassis/1/ThermalSubsystem/FanGroups'

local function get_fans_in_a_group(chassid, obj)
    local fans = {}
    local fans_slot = obj.FanSlots
    for _, i in ipairs(fans_slot) do
        fans[#fans + 1] = {
            ['@odata.id'] = '/redfish/v1/Chassis/' .. chassid .. '/ThermalSubsystem/Fans/' .. i
        }
    end

    return fans
end

function m.get_fangroups(chassisid)
    local fangroup = {}
    local fangroups = mdb.get_sub_objects(bus, FANGROUP_MDB_PATH, FANGROUP_MDB_INTF)
    for _, obj in pairs(fangroups) do
        fangroup[#fangroup + 1] = {
            ['GroupId'] = obj.Id,
            ['Fans'] = get_fans_in_a_group(chassisid, obj, obj.Id),
            ['ExpectedSpeedPercent'] = obj.ExpectedSpeedPercent
        }
    end
    table.sort(fangroup, function(a, b) return a['GroupId'] < b['GroupId'] end)
    
    return fangroup
end

local function get_sorted_fan_group_path(path_table)
    local res = {}
    for _, path in ipairs(path_table) do
        local obj = mdb.get_object(bus, path, FANGROUP_MDB_INTF)
        if obj then 
            res[obj.Id] = path
        end
    end
    return res
end

function m.get_changed_fan_group_path(path_table, fan_groups)
    local sorted_fangroup_path = get_sorted_fan_group_path(path_table)
    local res = {}
    for _, v in pairs(fan_groups) do
        if sorted_fangroup_path[v.GroupId] then
            table.insert(res, sorted_fangroup_path[v.GroupId])
        end
    end
    return res
end

function m.get_fan_expected_speed_percent(path_table, fan_groups)
    local sorted_fangroup_path = get_sorted_fan_group_path(path_table)
    local res = {}
    for _, v in pairs(fan_groups) do
        if sorted_fangroup_path[v.GroupId] then
            table.insert(res, v.ExpectedSpeedPercent)
        end
    end
    return res
end

return m