-- 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.


-- Description: fru相关全局数据
local class           = require 'mc.class'
local log             = require 'mc.logging'
local client          = require 'frudata.client'
local singleton       = require 'mc.singleton'
local persistence     = require 'fru_persistence'
local frudata_intf    = require 'frudata_intf'
local fru_singleton   = class()

function fru_singleton:ctor()
    self.version = ''
    self.update_status = {}
    self.is_fru_main_board_init = false
    self.slot_id = 0
    self.fru_uids = {}
    self.is_mcu_fru = {}
    local product_extra_format =
        persistence.get_instance():select_poweroff_data('Customize', 'BMCSet_FRUProductExtraFormat')
    self.product_extra_format = product_extra_format and tonumber(product_extra_format) or 0
    local ok, err = pcall(function()
        frudata_intf.set_product_extra_format(self.product_extra_format)
    end)
    if not ok then
        log:error('set product extra format failed, error[%s]', err)
    end
end

function fru_singleton:get_bmc_version()
    if self.version ~= '' then
        return self.version
    end

    client:ForeachFirmwareInfoObjects(function(obj)
        if obj.path == '/bmc/kepler/UpdateService/FirmwareInventory/ActiveBMC' then
            self.version = obj.Version
        end
    end)

    return self.version
end

function fru_singleton:get_slot_id(fru_id)
    if fru_id ~= 0 then
        -- 其他设备的槽位号，直接默认为 0
        return 0
    end

    -- 如果是节点，则根据节点的 NodeLocation 来提供槽位号，如果没有则默认为0
    return self.slot_id
end

function fru_singleton:init_slot_id(sender, path, properties)
    if properties['LocationId'] then
        self.slot_id = properties['LocationId']:value()
        log:notice("first get location id(%d)", self.slot_id)
    end
end

function fru_singleton:set_slot_id(properties)
    if properties['LocationId'] then
        self.slot_id = properties['LocationId']:value()
        log:notice('Update location id to (%d)', self.slot_id)
    end
end

return singleton(fru_singleton)
