-- 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 class = require "mc.class"
local abstract_cfg = require "pojo.boot.abstract_boot_option"
local boot_def = require "macros.boot_def"

local boot_valid = class(abstract_cfg)

function boot_valid:ctor(option_db_obj, system_id)
    boot_valid.super.init_db_info(self, option_db_obj, boot_def.VALID_FLAG, system_id)
end

-- 设置标记位
function boot_valid:set_boot_option_valid(selector, valid)
    local data = self.data
    local intreval = boot_def.BIOS_VALID_FLAG_INTREVAL
    local selector_arr_pos = math.floor(selector / intreval)
    if not data or not selector or not valid or
        not data[selector_arr_pos] then
        return false
    end

    data[selector_arr_pos] = data[selector_arr_pos] & 0xff
    -- 将selector所在位置清零
    local clear_zero = (~(1 << (selector % intreval))) & 0xff
    data[selector_arr_pos] = data[selector_arr_pos] & clear_zero
    -- 根据valid将selector所在位置置位
    local valid_data = (valid << (selector % intreval)) & 0xff
    data[selector_arr_pos] = data[selector_arr_pos] | valid_data
    data[selector_arr_pos] = data[selector_arr_pos] & 0xff

    self:update_db_info()
    return true
end

-- 获取标记位
function boot_valid:get_boot_option_valid(selector)
    local data = self.data
    if not data or not selector then
        return boot_def.BIOS_BOOT_OPTION_INVALID
    end

    local boot_num = boot_def.BIOS_BOOT_VALID_SEG_NUM
    if selector > (boot_num * 8) then
        return boot_def.BIOS_BOOT_OPTION_INVALID
    end

    local intreval = boot_def.BIOS_VALID_FLAG_INTREVAL
    local selector_arr_pos = math.floor(selector / intreval)
    local option_pos = data[selector_arr_pos]
    if not option_pos then
        return boot_def.BIOS_BOOT_OPTION_INVALID
    end

    local bit_pos = 1 << (selector % intreval)
    local valid = option_pos & bit_pos
    if valid == 0 then
        return boot_def.BIOS_BOOT_OPTION_INVALID
    end

    return boot_def.BIOS_BOOT_OPTION_VALID
end

return boot_valid