-- 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 worker = require 'worker.core'
local work = worker.new(0)

local ncsi_worker = {}
ncsi_worker.__index = ncsi_worker

function ncsi_worker.new()
    return setmetatable({}, ncsi_worker)
end

function ncsi_worker:start_ncsi_recv_task(db)
    local eth_name = "eth" .. db:select(db.NcsiNCInfo):first().EthId
    work:start(string.format([[
        local logging = require "mc.logging"
        local network = require 'network.core'
        local ncsi_core = require 'ncsi.ncsi_core'
        local skynet = require 'skynet'

        pcall(function()
            skynet.register_protocol({
                name = 'ncsi_packet_recv',
                id = 251,
                pack = skynet.pack,
                unpack = skynet.unpack
            })
        end)

        local ETH_NCSI_TYPE = 0x88F8
        local fd = network.socket(network.PF_PACKET, network.SOCK_RAW, network.htons(ETH_NCSI_TYPE))
        local eth_name = '%s'
        logging:notice('start ncsi recive task ' .. eth_name)
        local worker = ...
        while worker:is_running() do
            local data = ncsi_core.ncsi_receive_packet(fd, eth_name)
            if data ~= nil then
                skynet.send('network_adapter', 'ncsi_packet_recv', 'data', data)
            end
        end
        network.close(fd)
    ]], eth_name))
end

return ncsi_worker
