-- 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.ReadVersionData'
local mc_ipmi = require 'ipmi'
local log = require 'mc.logging'
local factory = require 'factory'
local skynet = require 'skynet'
local common = require 'external_interface.common'

local cc = mc_ipmi.types.Cc
local LAST_DATA = 0x80
local MIDDLE_DATA = 0X00

local ipmi_handler = {}
ipmi_handler.all_version = ""

local function response_error(code)
    return ipmi.ReadVersionDataRsp.new(code, LAST_DATA, "")
end

function ipmi_handler.read_version_data(req, ctx)
    local version_data
    local external_interface_handler = factory.get_obj("external_interface_handler")
    if req.VerType == common.ALL_VERSION then
        if req.FruId ~= 0 then
            return response_error(cc.ParmOutOfRange)
        end
        version_data = ipmi_handler.all_version
        skynet.fork(function ()
            ipmi_handler.all_version = external_interface_handler:get_all_version(req.FruId, ctx)
        end)
    else
        version_data = external_interface_handler:get_version_by_type(req.FruId, req.VerType, ctx)
    end

    local end_mask = req.Offset + req.Length >= #version_data and LAST_DATA or MIDDLE_DATA

    log:notice("read version complete: fruid - %s, type - %s, version data is %s",
        req.FruId, req.VerType, version_data)
    return ipmi.ReadVersionDataRsp.new(
        cc.Success, end_mask, string.sub(version_data, req.Offset, req.Offset + req.Length))
end

return ipmi_handler