-- 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 ipmi = require 'ipmi'
local singleton = require 'mc.singleton'
local msg = require 'lsw.ipmi.ipmi_message'
local log = require 'mc.logging'
local class = require 'mc.class'
local comp_code = ipmi.types.Cc

local ipmi_service = class()

local function reponse_port_link_status(port)
    local link_states = port:get_prop('LinkStatus')
    return msg.GetPortLinkStatusRsp.new(comp_code.Success, link_states)
end

local function reponse_port_speed(port)
    local speed_lsb = port:get_prop('Speed') & 0xff           -- 低8bit
    local speed_msb = (port:get_prop('Speed') & 0xff00) >> 8  -- 高8bit
    local auto_nego = port:get_prop('AutoNego')
    local duplex = port:get_prop('Duplex')
    log:notice("[lsw] reponse_port_speed SpeedLsb %s SpeedMsb %s AutoNego %s Duplex %s",
        speed_lsb, speed_msb, auto_nego, duplex)
    return msg.GetPortSpeedRsp.new(comp_code.Success, speed_lsb, speed_msb, auto_nego, duplex)
end

function ipmi_service:get_port_link_status(req, ctx)
    local port_id = req.PortId
    local switch_collections = self.mgt.switch_collection
    for _, switch in pairs(switch_collections) do
        local port = switch:get_port(port_id)
        if port then
            return reponse_port_link_status(port)
        end
    end
    return msg.GetPortLinkStatusRsp.new(comp_code.InvalidCommand)
end

function ipmi_service:get_port_speed(req, ctx)
    local port_id = req.PortId
    local switch_collections = self.mgt.switch_collection
    for _, switch in pairs(switch_collections) do
        local port = switch:get_port(port_id)
        if port then
            return reponse_port_speed(port)
        end
    end
    return msg.GetPortSpeedRsp.new(comp_code.InvalidCommand)
end

function ipmi_service:ctor(mgt)
    self.mgt = mgt
end

return singleton(ipmi_service)