-- 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 PUMPGROUP_MDB_INTF <const> = 'bmc.kepler.Chassis.PumpGroup'
local PUMPGROUP_MDB_PATH <const> = '/bmc/kepler/Chassis/1/ThermalSubsystem/PumpGroups'

local function get_pumps_in_a_group(chassid, obj)
    local pumps = {}
    local pumps_slot = obj.PumpSlots
    for _, i in ipairs(pumps_slot) do
        pumps[#pumps + 1] = {
            ['@odata.id'] = '/redfish/v1/Chassis/' .. chassid .. '/ThermalSubsystem/Pumps/' .. i
        }
    end

    return pumps
end

function m.get_pumpgroups(chassisid)
    local pumpgroup = {}
    local pumpgroups = mdb.get_sub_objects(bus, PUMPGROUP_MDB_PATH, PUMPGROUP_MDB_INTF)
    for _, obj in pairs(pumpgroups) do
        pumpgroup[#pumpgroup + 1] = {
            ['GroupId'] = obj.Id,
            ['Pumps'] = get_pumps_in_a_group(chassisid, obj),
            ['ExpectedSpeedPercent'] = obj.ExpectedSpeedPercent
        }
    end
    table.sort(pumpgroup, function(a, b) return a['GroupId'] < b['GroupId'] end)
    
    return pumpgroup
end

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

function m.get_changed_pump_group_path(path_table, pump_groups)
    local sorted_pumpgroup_path = get_sorted_pump_group_path(path_table)
    local res = {}
    for _, v in pairs(pump_groups) do
        if sorted_pumpgroup_path[v.GroupId] then
            table.insert(res, sorted_pumpgroup_path[v.GroupId])
        end
    end
    return res
end

function m.get_pump_expected_speed_percent(path_table, pump_groups)
    local sorted_pumpgroup_path = get_sorted_pump_group_path(path_table)
    local res = {}
    for _, v in pairs(pump_groups) do
        if sorted_pumpgroup_path[v.GroupId] then
            table.insert(res, v.ExpectedSpeedPercent)
        end
    end
    return res
end

return m