-- 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: 用于统计升级任务进度的类，当前每个子任务所占百分比相同，当前最大支持160个子任务
local progress_statistics = {}
progress_statistics.__index = progress_statistics

local MAX_TASK_CNT<const> = 160 -- 最大支持的子任务数量

function progress_statistics.new(min_progress, max_progress, sub_task_cnt)
    if min_progress >= max_progress or sub_task_cnt > MAX_TASK_CNT then
        return nil
    end
    local obj = {}
    obj.min_progress = min_progress
    obj.max_progress = max_progress
    obj.space_for_progress_growth = max_progress - min_progress
    obj.sub_task_cnt = sub_task_cnt
    obj.cur_progress = min_progress
    obj.sub_task_progress = {}
    for _=1, sub_task_cnt do
        table.insert(obj.sub_task_progress, 0)
    end

    return setmetatable(obj, progress_statistics)
end

--- @function 发送文件给MCU
--- @param task_idx number 子任务的索引
--- @param progress number 子任务当前的进度(0-100)
--- @return number 当前进度
function progress_statistics:set_sub_task_progress(task_idx, progress)
    if progress < 0 or progress < self.sub_task_progress[task_idx] or progress > 100 then
        return -1
    end

    self.cur_progress = self.cur_progress + (progress - self.sub_task_progress[task_idx]) / 100 *
        (self.space_for_progress_growth / self.sub_task_cnt)

    self.sub_task_progress[task_idx] = progress

    return math.floor(self.cur_progress)
end

function progress_statistics:get_current_progress()
    return math.floor(self.cur_progress)
end

return progress_statistics