-- Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
--
-- this file licensed under the 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 log = require 'mc.logging'
local client = require 'thermal_mgmt.client'
local props = require 'basic_cooling.define.cooling_properties'
local mdb = require 'mc.mdb'
local base = require 'basic_cooling.data_keeping.base'
local fans = require 'basic_cooling.cooling_device.cooling_fans'
local utils = require 'basic_cooling.cooling_utils'

local fan_group_data_keeping = class(base)

function fan_group_data_keeping:init()
    self.obj_name = 'FanGroup'
    -- 监听的资源树路径
    self.path = "/bmc/kepler/Chassis/:ChassisId/ThermalSubsystem/FanGroups/:Id"
    -- 监听的接口
    self.interfaces_table = {
        ['bmc.kepler.Chassis.FanGroup'] = client.ForeachFanGroupObjects
    }
    -- 监听的属性
    self.props_table = {
        [props.EXPECTED_SPEED_PERCENT] = true
    }
    self.super.init(self)
    self.fans_instance = fans.get_instance()
    self.fan_control_table = {}
end

function fan_group_data_keeping:properties_changed()
    return client:OnFanGroupPropertiesChanged(function (prop_value, path, interface)
        self:property_changed_callback(path, interface, prop_value)
    end)
end

function fan_group_data_keeping:action_after_property_changed(path, interface, prop, value)
    -- 获取修改的资源树对象
    local fan_group = mdb.get_object(self.bus, path, interface)
    -- 更新风扇组转速
    self:update_fan_group_control_table(fan_group)
end

function fan_group_data_keeping:action_after_obj_added(path, interface)
    local fan_group = mdb.get_object(self.bus, path, interface)
    self:update_fan_group_control_table(fan_group)
end

function fan_group_data_keeping:update_fan_group_control_table(fan_group)
    local fan_slots_table = {string.byte(fan_group.FanSlots, 1, -1)}
    for _, fan_id in pairs(fan_slots_table) do
        self.fan_control_table[fan_id] = fan_group.ExpectedSpeedPercent
    end
    local policy_info = utils.parse_table_info(self.fan_control_table)
    log:notice(" Update fan group(%s), control table speed percent(%s)", fan_group.Id, policy_info)
end

function fan_group_data_keeping:get_fan_group_control_table()
    return self.fan_control_table
end

return fan_group_data_keeping