-- 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: 模拟Vrd升级
local log = require 'mc.logging'
local service = require 'general_hardware_app'
local upgrade_object = require 'mcu.upgrade.upgrade_object'

local SIM_INTF <const> = 'bmc.kepler.Manufacture.Simulate'
local vrd_upgrade_sim = {
    boards_obj = service:CreateBoards(1)
}

local RET_OK = 0
local RET_ERR = -1
local RETRY_ERR = 2

local function sim_func(self, dir)
    local lib_size = 0

    log:notice("---STEP: 1")
    -- 获取升级对象的升级文件路径
    local file_path, bin_size = self:get_file_path(dir)
    if not file_path then
        log:error("failed to get MCU upgrade file_path")
        return RET_ERR
    end
    self.path = string.sub(file_path, #dir + 1, -1):gsub("%.bin$", "")

    -- 判断可升级状态
    if self:is_upgradeable(lib_size, bin_size) == RET_ERR then
        log:error("not support upgrade now")
        return RET_ERR
    end
    log:notice("Simulate upgrade successfully!")
    return RET_OK
end

local act_func = upgrade_object.retry_upgrade

function vrd_upgrade_sim:init()
    self.signal = {}
    table.insert(self.signal, self.boards_obj[SIM_INTF].property_changed:on(function (name, value)
        if name == 'VrdUpgradeSimulated' then
            upgrade_object.retry_upgrade = ({
                [0] = act_func,
                [1] = sim_func
            })[value]
            log:notice('Changee upgrade %s', value == 0 and 'actual' or 'simulated')
        end
    end))
end

return vrd_upgrade_sim