-- 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 class = require('mc.class')
local skynet = require('skynet')
local object_defs = require('object_defs')
local log = require('mc.logging')
local stream = class()
local merge_work_flag = {}
local merge_work_addr = {}

local SKYNET_CALL_TIMEOUT <const> = 18000 -- 18000: 超时时间3分钟

local function get_merge_key(object)
    local need_merge = object_defs[object.class_name].need_merge
    if need_merge == true then
        return object.class_name
    elseif type(need_merge) == 'function' then
        return need_merge(object)
    end
    return nil
end

-- 检查是否成功获取到work服务地址
local function check_work_addr(self)
    if self.work == nil then
        repeat
            self.work = merge_work_addr[self.merge_key]
            skynet.sleep(20)
        until self.work ~= nil
    end
end

function stream:ctor(object)
    self.name = object.name
    self.bus_type = object.class_name
    local merge_key = get_merge_key(object)
    if merge_key then
        -- 对于需要合并的bus服务, 同一分组只创建一个skynet服务
        if not merge_work_flag[merge_key] then
            merge_work_flag[merge_key] = true
            merge_work_addr[merge_key] = skynet.newservice('hwproxy/service/work', object.name)
        end
        self.merge_key = merge_key
        self.work = merge_work_addr[merge_key]
        check_work_addr(self)
        return
    end
    self.work = skynet.newservice('hwproxy/service/work', object.name)
end

local function get_rw_detail(func, obj, ...)
    return '{function: ' .. func .. ', path: ' .. obj.path .. '}'
end

local function get_rt_rw_detail(_, name)
    return '{accessor: ' .. name .. '}'
end

local function get_chip_detail(obj, ...)
    return '{path: ' .. obj.path .. '}'
end

local request_detail_map = {}
request_detail_map['read_write_func'] = get_rw_detail
request_detail_map['cpld_upg_request'] = get_rw_detail
request_detail_map['realtime_read'] = get_rt_rw_detail
request_detail_map['realtime_write'] = get_rt_rw_detail
request_detail_map['chip_test'] = get_chip_detail
request_detail_map['stop_chip_scanners'] = get_chip_detail
request_detail_map['restart_chip_scanners'] = get_chip_detail
request_detail_map['plugin_request'] = get_chip_detail

local function get_request_detail(method, ...)
    if request_detail_map[method] then
        local ok, ret = pcall(request_detail_map[method], ...)
        if ok then
            return ret
        end
    end

    return 'null'
end

local function skynet_call(work, flag, method, name, ...)
    local call_back = false
    local detail = get_request_detail(method, ...)
    local handler
    handler = skynet.timeout(SKYNET_CALL_TIMEOUT, function()
        handler = nil
        if call_back then
            return
        end
        log:hw_stream_error(
            'work service: %s may be suspended because %s request does not respond, location: %s',
            name,
            method,
            detail
        )
    end)

    local process = function(ok, ret, ...)
        call_back = true
        if handler then
            skynet.killthread(handler)
        end

        if not ok then
            error(ret)
        end
        return ret, ...
    end

    return process(skynet.call(work, flag, method, name, ...))
end

local function process_result(ok, ret, ...)
    if not ok then
        error(ret)
    end
    return ret, ...
end

function stream:call(method, ...)
    check_work_addr(self)
    return skynet_call(self.work, 'lua', method, self.name, ...)
end

function stream:send(method, ...)
    check_work_addr(self)
    return process_result(skynet.send(self.work, 'lua', method, self.name, ...))
end

local bus = class()

function bus:ctor(object)
    self.name = object.name
    self.stream = stream.new(object)
    self.need_scan = false -- 主线程不扫描
    self.task_count = 0 -- 读写请求任务数
end

function bus:add_object(class_name, object, position)
    return self.stream:send('add_object', class_name, object, position)
end

function bus:add_object_complete(position, topo_data, monitor_service)
    return self.stream:send('add_object_complete', position, topo_data, monitor_service)
end

function bus:delete_object(class_name, object, position)
    return self.stream:send('delete_object', class_name, object, position)
end

function bus:delete_object_complete(position)
    return self.stream:send('delete_object_complete', position)
end

function bus:set_raw_dbus(...)
    return self.stream:send('set_raw_dbus', ...)
end

function bus:add_task_count()
    self.task_count = self.task_count + 1
    if self.on_task_added then
        self.on_task_added(self.task_count)
    end
end

function bus:clear_task_count()
    self.task_count = 0
end

function bus:register_task_added_cb(cb)
    self.on_task_added = cb
end

-- work服务重启后刷新分组缓存的地址, 使后续新建的同组通道指向新服务
function bus.update_work_addr(merge_key, addr)
    merge_work_addr[merge_key] = addr
end

return bus