-- 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'
require 'object_manager.basic'

---@class c_object_index: c_basic_class
---@field fold fun(self: c_object_index, cb: (fun(acc: any, obj: any, key: string):any) , acc: any): any[]
---@field safe_fold fun(self: c_object_index, cb: (fun(acc: any, obj: any, key: string):any) , acc: any): any[]
local c_object_index = class()

local function fold_objects(objects, cb, acc)
    local exit_loop
    for key, obj in pairs(objects) do
        acc, exit_loop = cb(acc, obj, key)
        if exit_loop then
            break
        end
    end
    return acc
end

function c_object_index:ctor(keys)
    self.keys = keys
    self.objects = {}
end

function c_object_index:reset()
    self.objects = {}
end

function c_object_index:copy_objects()
    return self:fold(function(acc, obj, key)
        acc[key] = obj
        return acc
    end, {})
end

function c_object_index:fold(cb, acc)
    return fold_objects(self.objects, cb, acc)
end

function c_object_index:safe_fold(cb, acc)
    return fold_objects(self:copy_objects(), cb, acc)
end

function c_object_index:find_object(cb)
    return fold_objects(self.objects, function(_, object)
        if cb(object) then
            return object, true
        end
    end)
end

function c_object_index:get_object(key)
    if not key then
        return nil
    end
    return self.objects[key]
end

function c_object_index:add_object(key, object)
    self.objects[key] = object
end

function c_object_index:del_object(key)
    self.objects[key] = nil
end

return c_object_index