-- 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 cmn = require 'common'
local log = require 'mc.logging'
local class = require 'mc.class'

local MAX_RETRY_TIMES<const> = 3
local c_pcie_slot = class()

function c_pcie_slot:ctor(mds_obj, position, bus)
    self.position = position
    self.mds_obj = mds_obj
    self.bus = bus
end

local HYPER_CARD_TYPE <const> = 57
function c_pcie_slot:set_power_state(state, SupportedComponentTypes)
    local ok
    local err
    for _, type in pairs(SupportedComponentTypes) do
        if  type == HYPER_CARD_TYPE then
            ok, err = pcall(function(...)
                self.mds_obj.PowerOnSwitch = state == "Off" and 0 or 1
            end)
            if not ok then
                log:error('[PCIeSlot] set power to %s failed: %s', state, err)
                return false
            end
            return true
        end
    end
    for i = 1, MAX_RETRY_TIMES do
        ok, err = pcall(function ()
            self.mds_obj.ReadyToRemove = (state == "Off" and 1 or 0)
        end)
        if ok then
            return true
        end
        cmn.skynet.sleep(100)
    end
    log:error('[PCIeSlot] set power to %s failed: %s', state, err)
    return false
end

return c_pcie_slot