-- 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 class = require 'mc.class'
local singleton = require 'mc.singleton'
local mdb_service = require 'mc.mdb.mdb_service'

local object_service = class()

function object_service:ctor(bus)
    self.bus = bus
end

function object_service:get_obj_path_list(path, interface)
    if not self.bus then
        return {}
    end

    local rsp = mdb_service.get_sub_paths(self.bus, path, 1, {interface})
    return rsp.SubPaths
end

function object_service:get_object(service_name, path, interface)
    if not self.bus then
        return
    end
    local obj = self.bus:call(service_name, path, 'org.freedesktop.DBus.Properties', 'GetAll', 's',
        interface)
    return obj
end

function object_service:get_object_list(service_name, path, interface)
    if not self.bus then
        return {}
    end
    local obj_list = {}
    local path_list = self:get_obj_path_list(path, interface)
    for _, p in pairs(path_list) do
        local obj = self:get_object(service_name, p, interface)
        obj.path = p
        table.insert(obj_list, obj)
    end
    return obj_list
end

return singleton(object_service)