-- 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 singleton = require 'mc.singleton'
local c_battery = require 'battery.battery_object'
local class = require 'mc.class'
local signal = require 'mc.signal'
local c_tasks = require 'mc.orm.tasks'
local log = require 'mc.logging'

local BATTERY_NAME <const> = 'Battery'

local c_battery_collection = class(nil, nil, true)

function c_battery_collection:ctor(storage_app_service)
    self.battery_list = {}
    self.storage_app_service = storage_app_service
    self.object_manager = storage_app_service.mc_obj_manager
    self.on_controller_commu_changed = signal.new()
end

function  c_battery_collection:init()
    self.on_controller_commu_changed:on(function(mctp_state, controller_id)
        --重新更新Battery的RefController；因为Battery的自发现可能位于Controller前面
        c_battery.collection:fold(function(acc, obj, key)
            local controller = obj:get_parent()
            if controller and controller.Id == controller_id then
                obj.RefController = controller.Id
            end
        end, {})
        if mctp_state then
            c_battery.collection:fold(function(acc, obj, key)
                if obj.RefController == controller_id then
                    obj.enable_request = true
                end
            end, {})
        else
            c_battery.collection:fold(function(acc, obj, key)
                if obj.RefController == controller_id then
                    obj:set_default_values()
                end
            end, {})
        end
    end)
    self:start_update_battery_info_task()
end

-- battery走自发现流程：os下电时候，battery对象依然存在；发送信号：on_controller_commu_changed通知下电
function c_battery_collection:start_update_battery_info_task()
    c_tasks.get_instance():new_task('update battery info task'):loop(function(task)
        c_battery.collection:fold(function(acc, obj, key)
            pcall(obj.get_battery_info, obj)
        end, {})
    end):set_timeout_ms(60000)
end

function c_battery_collection:get_capcacitance_by_controller_id(controller_id)
    return c_battery.collection:find({ RefController = controller_id })
end


return singleton(c_battery_collection)
