-- 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 class = require 'mc.class'
local skynet = require 'skynet'
local enums = require 'types.enums'
local utils = require 'types.utils'

local c_power_button = class()

function c_power_button:ctor(id)
    self.system_id = id
    self.objs = {}
end

function c_power_button:insert_obj(object)
    if not object.IsValid then
        log:error_easy('[System:%s]ignore invalid PowerButton obj', self.system_id)
        return
    end
    self.objs[object.FruID] = object
    log:notice_easy("[System:%s]insert power_button fru%s object successfully, uptime: %s.",
        self.system_id, object.FruID, utils.uptime())
end

local function do_push_operation(objs, prop, value)
    local ok, msg = pcall(function ()
        objs[prop] = value
    end)
    if not ok then
        log:error_easy('set prop %s to %s failed, error_msg:%s', prop, value, msg)
    end
end

function c_power_button:push_button_short(fruid)
    -- write ShortPushPowerButton property on dbus property
    local id = fruid or enums.FruId.OS
    if not self.objs[id] then
        log:notice_easy('[System:%s]The object does not exist', self.system_id)
        return enums.RetValue.ERR
    end
    log:notice_easy('[System:%s]prepate to send short button signal through hwproxy Accessor', self.system_id)
    do_push_operation(self.objs[id], 'ShortPushButton', 0)
    skynet.sleep(100)
    do_push_operation(self.objs[id], 'ShortPushButton', 1)
    log:notice_easy('[System:%s]Notify fru%s cpld to send short button signal through hwproxy Accessor',
        self.system_id, id)
    return enums.RetValue.OK
end

function c_power_button:push_button_long(fruid)
    local id = fruid or enums.FruId.OS
    -- write LongPushPowerButton property on dbus property
    if id == enums.FruId.GlobalDomain then
        log:error_easy('[System:%s]fruid is 4, no need to push long button', self.system_id)
        return enums.RetValue.ERR
    end
    log:notice_easy('[System:%s]prepate to send long button signal through hwproxy Accessor', self.system_id)
    do_push_operation(self.objs[enums.FruId.OS], 'LongPushButton', 0)
    skynet.sleep(100)
    do_push_operation(self.objs[enums.FruId.OS], 'LongPushButton', 1)
    log:notice_easy('[System:%s]Notify cpld to send long button signal through hwproxy Accessor', self.system_id)
    return enums.RetValue.OK
end

return c_power_button