-- 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.SetChipInfo'
local mc_ipmi = require 'ipmi'
local log = require 'mc.logging'
local factory = require 'factory'

local cc = mc_ipmi.types.Cc

local ipmi_handler = {}

function ipmi_handler.set_chip_info(req, ctx)
    local component_type = req.ComponentType
    local component_slot = req.ComponentSlot
    local chip_type = req.ChipType
    local length = req.Length
    local data = req.Data

    if length == 0 or (chip_type == 1 and length ~= 1) then
        mc_ipmi.ipmi_operation_log(ctx, 'manufacture', "Set device chip info failed")
        log:error('Parameter is invalid: length = %d', length)
        return ipmi.SetChipInfoRsp.new(cc.ParmOutOfRange)
    end

    local device_chip_service = factory.get_obj("device_chip_service")
    local ok
    if component_type == 0x42 and component_slot == 0 then
        ok = device_chip_service:set_device_chip_by_type_slot(1, 0, data)
    else
        ok = device_chip_service:set_device_chip_by_type_slot(component_type, component_slot, data)
    end
    if not ok then
        mc_ipmi.ipmi_operation_log(ctx, 'manufacture', "Set device chip info failed")
        log:error('Chip not found, type = %d, slot = %d.', component_type, component_slot)
        return ipmi.SetChipInfoRsp.new(cc.ParmOutOfRange)
    end
    log:notice("set chip type = %s, slot = %s, value = %s successfully", component_type, component_slot, data)
    mc_ipmi.ipmi_operation_log(ctx, 'manufacture', 'Set device chip info (type is %s, slot is %s, value is %s) successfully.',
        component_type, component_slot, data)
    return ipmi.SetChipInfoRsp.new(cc.Success)
end

return ipmi_handler