-- Copyright (c) 2025 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 class = require 'mc.class'
local process_channel = require 'domain.bios_firmware.package.channel.firmware_process_channel'
local _, hisport_flash = pcall(require, 'libmgmt_protocol.bios.infrastructure.hisport_flash')
local skynet = require 'skynet'
local HisportChannel = class(process_channel)

local E_OK<const> = 0
function HisportChannel:ctor()
    HisportChannel.super.ctor(self, 'HisportChannel')
end

function HisportChannel:upgrade(ctx, properties)
    if not ctx or not properties or not ctx.BinPath or not ctx.BlockChip or
        not ctx.FlashChip or not properties.Offset or not properties.Length then
        error('hisport channel: invalid param')
    end
    skynet.sleep(50)
    if hisport_flash.erase_all_flash(ctx.FlashChip) ~= E_OK then
        error('erase all flash failed')
    end
    hisport_flash.wait_erase_finish(ctx.BlockChip)
    if hisport_flash.hisport_flash_copy(ctx.BlockChip, ctx.BinPath,
        properties.Offset, properties.Length) ~= E_OK then
        error('write update region to flash failed')
    end
end

return HisportChannel