-- Copyright (c) 2026 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 skynet = require('skynet')
require('skynet.manager')
local work_app = require('hwproxy_work_app')
local logging = require('mc.logging')
logging:set_log_module_name('hwproxy')
local bus_object_name = ...

local STATUS_NORMAL <const> = 0
local STATUS_SUSPEND <const> = 1
local SUSPEND_BLOCK_TIME <const> = 12000

local service_status = STATUS_NORMAL

local function change_debuglog_path(option)
    if not option then
        return
    end

    logging:setLevel(logging.INFO)
    logging.info = function(self, fmt, ...)
        skynet.error('INFO', string.format(fmt, ...))
    end
    logging.error = function(self, fmt, ...)
        skynet.error('ERROR', string.format(fmt, ...))
    end
    logging.notice = function(self, fmt, ...)
        skynet.error('NOTICE', string.format(fmt, ...))
    end
end

change_debuglog_path(false)

local cmd_normal = {}

function cmd_normal.heart_beat()
    return true
end

local cmd_ctrl = {}

function cmd_ctrl.mock_bus_ctrl(action)
    if action == 'suspend' then
        service_status = STATUS_SUSPEND
    else
        service_status = STATUS_NORMAL
    end
    logging:mcf_notice('%s work service set status to %s', bus_object_name, action)
end

local service

local function call(method, ...)
    if cmd_ctrl[method] then
        return cmd_ctrl[method](...)
    end
    if service_status == STATUS_SUSPEND then
        skynet.sleep(SUSPEND_BLOCK_TIME)
    end
    if cmd_normal[method] then
        return cmd_normal[method](...)
    end
    if service[method] then
        return pcall(service[method], service, ...)
    end
end

skynet.start(function()
    service = work_app.new()
    skynet.dispatch('lua', function(_, _, ...)
        skynet.ret(skynet.pack(call(...)))
    end)
end)