-- 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 log = require 'mc.logging'
local cjson = require 'cjson'

local m = {}

local function get_agent_ports_object(mdb, bus)
    local path = '/bmc/kepler/Systems/1/Sms/1/AgentPorts'
    local interface = 'bmc.kepler.Systems.Sms.AgentPorts'
    local ok, obj = pcall(function ()
        return mdb.get_object(bus, path, interface)
    end)
    if not ok then
        log:debug('Get current value file failed, ret = %s', obj)
        return nil
    end

    return obj
end

function m.is_valid_port(max_port, min_port)
    if max_port == nil and min_port == nil then
        return false
    end

    if max_port and min_port then
        return max_port - min_port > 14
    end

    local agent_ports_obj = get_agent_ports_object(mdb, bus)
    if agent_ports_obj == nil then
        log:debug('Get agent_ports_obj failed')
        return false
    end

    if max_port == nil then
        local content = agent_ports_obj.ServerMaxPort
        return content - min_port > 14
    end

    if min_port == nil then
        local content = agent_ports_obj.ServerMinPort
        return max_port - content > 14
    end

    return false
end

function m.format_sms_update_service_odataid(heart_state, sms_props)
    if sms_props.Type ~= 'InbandManagement' or not sms_props.Registered or heart_state ~= 0 or
        (sms_props.ChannelType == 1 and not sms_props.CdevChannelEnabled) then
        return cjson.null
    end

    local rsp = cjson.json_object_new_array()
    local oid = cjson.json_object_new_object()
    oid['@odata.id'] = '/redfish/v1/Sms/1/UpdateService'
    rsp[#rsp + 1] = oid
    return rsp
end

return m
