-- 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 log = require('mc.logging')
local task = require('mc.mdb.task_mgmt')

local create_task_err_code <const> = task.create_code
local update_task_err_code <const> = task.update_code
local task_state = task.state

local module = {}

-- 创建任务
function module.create_task(bus, task_name, path)
    local res, task_err, id = task.create_task(bus, task_name, path)
    if res ~= create_task_err_code.TASK_CREATE_SUCCESSFUL then
        log:error('[sync_task] Create task failed, task_name=%s, path=%s, res=%d', task_name, path, res)
        error(task_err)
    end

    return id
end

-- 更新任务属性
function module.update_task_prop(task_id, prop)
    local res = task.update_task(task_id, prop)
    if res ~= update_task_err_code.TASK_UPDATE_SUCCESSFUL then
        log:error('[Storage]Update task failed, res: %d', res)
    end
end

-- 获取任务状态
function module.get_task_running(task_id)
    local task_obj = task.get_task_obj(task_id)
    --未获取到任务对象说明任务已销毁
    if not task_obj then
        return false
    end
    local state = task_obj.State
    if
        state == task_state.Stopping
        or state == task_state.Completed
        or state == task_state.Killed
        or state == task_state.Exception
        or state == task_state.Cancelled
    then
        return false
    end
    return true
end

-- 删除任务
function module.destroy_task(task_id)
    task.destroy_task(task_id)
end

return module