-- 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 ipmi = require 'manufacture.ipmi.cmds.GetChipInfo'
local mc_ipmi = require 'ipmi'
local log = require 'mc.logging'
local factory = require 'factory'
local bs = require 'mc.bitstring'

local cc = mc_ipmi.types.Cc

local ipmi_handler = {}

local resp_str = bs.new("<<data>>")
function ipmi_handler.get_chip_info(req, ctx)
    local component_type = req.ComponentType
    local component_slot = req.ComponentSlot
    local chip_type = req.ChipType
    local length = req.Length

    if length == 0 or chip_type ~= 1 then
        log:error('Parameter is invalid: length = %s, chip_type = %s', length, chip_type)
        return ipmi.GetChipInfoRsp.new(cc.ParmOutOfRange, 0, "")
    end

    local device_chip_service = factory.get_obj("device_chip_service")
    local ok
    local data
    -- 出于兼容性考虑，将type=1,slot=0的设备作为VGA设备
    if component_type == 0x42 and component_slot == 0 then
        ok, data = device_chip_service:get_device_chip_by_type_slot(1, 0)
    else
        ok, data = device_chip_service:get_device_chip_by_type_slot(component_type, component_slot)
    end
    if not ok then
        log:error('Chip not found, type = %d, slot = %d.', component_type, component_slot)
        return ipmi.GetChipInfoRsp.new(cc.ParmOutOfRange, 0, "")
    end
    log:notice("get chip type = %s, slot = %s, value = %s successfully", component_type, component_slot, data)
    return ipmi.GetChipInfoRsp.new(cc.Success, 0, resp_str:pack({data = data}))
end

return ipmi_handler