-- 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_ipv6_address = c_object('IPv6Address')

function c_ipv6_address.create_mdb_object(value)
    local app = c_object_manage.get_instance().app
    return app:CreateIPv6Address(1, value.NetworkAdapterObjectName, value.NetworkPortObjectName,
        str_hash(value.Address), function(obj)
            obj.Address = value.Address
            obj.AddressState = value.AddressState
            obj.AddressOrigin = value.AddressOrigin
            obj.PrefixLength = value.PrefixLength
            obj.NetworkAdapterObjectName = value.NetworkAdapterObjectName
            obj.NetworkPortObjectName = value.NetworkPortObjectName
            obj.Gateway = value.Gateway
            obj.PortID = value.PortID
            obj.NetworkAdapterId = value.NetworkAdapterId
        end)
end

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

    value.NetworkAdapterObjectName = na_object_name
    value.NetworkPortObjectName = np_object_name
    value.AddressState = addr.AddressState
    value.AddressOrigin = addr.AddressOrigin
    value.PrefixLength = addr.PrefixLength
    value.Gateway = addr.Gateway
    return db_addr or c_ipv6_address.__table(value)
end

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

return c_ipv6_address
