-- 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 unit_manager = require 'unit_manager.unit_manager'
local card_manager = require 'card_manager.card_manager'
local dpu_service = require 'dpu_service.dpu_service'
local log = require 'mc.logging'

local fw_manager = {}

local unit_types = {'BCU', 'EXU', 'SEU', 'CLU', 'IEU', 'PSU', 'ACU', 'PEU'}
function fw_manager:get_device_name_by_position(fw_type, position)
    local device_name
    for _, v in pairs(unit_types) do
        if fw_type == v then
            device_name = unit_manager.get_instance():get_device_name(position)
            break
        end
    end
    -- PsuBoard电源板对外固件信息需要显示为PSU
    if fw_type == 'PSU' and device_name and string.find(device_name, "PsuBoard") then
        device_name = string.gsub(device_name, 'PsuBoard', 'PSU')
        goto exit
    end
    if fw_type == 'NIC' then
        device_name = card_manager.get_instance():get_device_name(position)
        goto exit
    end
    if fw_type == 'SDI' or fw_type == 'DPU' then
        device_name = 'PCIe' .. dpu_service.get_instance():get_slot_id(position)
        goto exit
    end
    if fw_type == 'PSR' then
        device_name = 'Product'
    end

    ::exit::
    if not device_name then
        device_name = 'NA'
    end
    log:info('[FW_Manager]get device name by %s and %s : %s', fw_type, position, device_name)
    return device_name
end

function fw_manager:get_node_id_by_position(fw_type, position)
    local node_id
    for _, v in pairs(unit_types) do
        if fw_type == v then
            node_id = unit_manager.get_instance():get_node_id(position)
            break
        end
    end
    log:info('[FW_Manager]get node id by %s and %s : %s', fw_type, position, node_id)
    return node_id
end

function fw_manager:generate_related_item_path(node_id)
    return node_id and '/redfish/v1/Chassis/1/Boards/' .. node_id or ''
end

function fw_manager:get_related_item_by_position(fw_type, position)
    local node_id
    node_id = fw_manager:get_node_id_by_position(fw_type, position)
    return fw_manager:generate_related_item_path(node_id)
end

return fw_manager