/* 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.
 */
#include "l_array.h"
#include "l_sml_adapter.h"

#include "ld.h"

namespace sml {
static int32_t update_array_info(lua_State *L, SML_ARRAY_INFO_S *info, uint8_t ctrl_index, uint16_t array_target_id)
{
    if (auto ret = l_sml_adapter::sml_adapter_get_array_info(ctrl_index, array_target_id, info); ret != RET_OK) {
        lua_pushinteger(L, ret);
        lua_error(L);
    }
    return 1;
}

static luawrap::n_ret get_free_blocks_space(lua_State *L, SML_ARRAY_INFO_S *info)
{
    return push_array(L, info->free_blocks_space, info->free_blocks_count);
}

static luawrap::n_ret get_ld_ids(lua_State *L, SML_ARRAY_INFO_S *info)
{
    return push_array(L, info->ld_ids, info->ld_count);
}

static luawrap::n_ret get_pd_ids(lua_State *L, SML_ARRAY_INFO_S *info)
{
    return push_array(L, info->pd_ids, info->pd_count);
}

static luawrap::n_ret get_pd_slots(lua_State *L, SML_ARRAY_INFO_S *info)
{
    return push_array(L, info->pd_slots, info->pd_count);
}

static luawrap::n_ret get_pd_enclosures(lua_State *L, SML_ARRAY_INFO_S *info)
{
    return push_array(L, info->pd_enclosures, info->pd_count);
}

void l_array::def_properties(lua_State *L, luawrap::lua_class<SML_ARRAY_INFO_S> &cls)
{
    cls.def_readonly("last_update_timestamp", &SML_ARRAY_INFO_S::last_update_timestamp);
    cls.def_readonly("used_space", &SML_ARRAY_INFO_S::used_space);
    cls.def_readonly("total_free_space", &SML_ARRAY_INFO_S::total_free_space);
    cls.def_property("free_blocks_space", c_func_wrap(L, get_free_blocks_space));
    cls.def_property("ld_ids", c_func_wrap(L, get_ld_ids));
    cls.def_property("pd_ids", c_func_wrap(L, get_pd_ids));
    cls.def_property("pd_slots", c_func_wrap(L, get_pd_slots));
    cls.def_property("pd_enclosures", c_func_wrap(L, get_pd_enclosures));
}

void l_array::register_to(lua_State *L, luawrap::stack_table &t)
{
    luawrap::restore_stack_top _s(L);

    // 导出 SML_ARRAY_INFO_S 结构给 lua 使用
    auto cls = luawrap::lua_class<SML_ARRAY_INFO_S>(L).ctor<>();
    cls.def("reset_zero", c_func_wrap(L, reset_zero<SML_ARRAY_INFO_S>));
    cls.def("update", c_func_wrap(L, update_array_info));
    def_properties(L, cls);

    t.set("SML_ARRAY_INFO_S", cls);
}
}  // namespace sml
