-- Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
-- 
-- this file licensed under the 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 utils = require 'mc.utils'
local class = require 'mc.class'
local log = require 'mc.logging'
local scheduler = require 'protocol_open.transport.scheduler'

local hw_communicator = class()

function hw_communicator:_send_data(params)
    if not self.protocols[params.protocol] then
        log:error('protocol not support, %s', params.protocol)
        return nil
    end
    return self.protocols[params.protocol]:send_request(params.request)
end

function hw_communicator:on_demand(params, parser)
    return {
        value = function()
            local result = self:_send_data(params)
            if not result then
                return nil
            end
            if not parser or #result == 0 then
                return true
            end

            return parser(result)
        end
    }
end

function hw_communicator:on_schedule(params, parser)
    local cache = self.schedulers[params.name]

    if cache then
        for _, s in ipairs(cache) do
            if utils.table_compare(s.params, params) then
                return s
            end
        end
    end

    local s = scheduler.new(self._send_data, self, params, parser)
    if not self.schedulers[params.name] then
        self.schedulers[params.name] = {}
    end
    table.insert(self.schedulers[params.name], s)
    return s

end

function hw_communicator:set_protocols(protocols)
    self.protocols = protocols
end

function hw_communicator:ctor()
    self.schedulers = {}
    self.protocols = {}
end

return hw_communicator