-- 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 c_object = require 'mc.orm.object'
local c_object_manage = require 'mc.orm.object_manage'
local utils = require 'utils.core'
local str_hash = utils.str_hash

local c_vlan_ipv4_address = c_object('VLANIPv4Address')

function c_vlan_ipv4_address.create_mdb_object(value)
    local app = c_object_manage.get_instance().app
    return app:CreateVLANIPv4Address(1, value.NetworkAdapterObjectName, value.NetworkPortObjectName,
        value.VLANId, str_hash(value.Address), function(obj)
            obj.Address = value.Address
            obj.SubnetMask = value.SubnetMask
            obj.Gateway = value.Gateway
            obj.AddressOrigin = value.AddressOrigin
            obj.NetworkAdapterObjectName = value.NetworkAdapterObjectName
            obj.NetworkPortObjectName = value.NetworkPortObjectName
            obj.PortID = value.PortID
            obj.NetworkAdapterId = value.NetworkAdapterId
            obj.VLANId = value.VLANId
        end)
end

function c_vlan_ipv4_address.insert_or_update(port_id, na_id, na_object_name, np_object_name,
    VLANId, addr)
    local value = {
        PortID = port_id,
        NetworkAdapterId = na_id,
        VLANId = VLANId,
        Address = addr.Address
    }
    local db_addr = c_vlan_ipv4_address.collection:find(value)
    if db_addr then
        value = db_addr
    end

    value.NetworkAdapterObjectName = na_object_name
    value.NetworkPortObjectName = np_object_name
    value.SubnetMask = addr.SubnetMask
    value.Gateway = addr.Gateway
    value.AddressOrigin = addr.AddressOrigin
    return db_addr or c_vlan_ipv4_address.__table(value)
end

function c_vlan_ipv4_address.get_addresses(port_id, na_id, vlan_id)
    return c_vlan_ipv4_address.collection:fetch({PortID = port_id, NetworkAdapterId = na_id, VLANId = vlan_id})
end

return c_vlan_ipv4_address
