# Copyright (c) 2012 VMware, Inc.
# Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack Foundation
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Utility functions for ESX Networking.
"""
from oslo_log import log as logging
from oslo_vmware import exceptions as vexc
from oslo_vmware import vim_util as vutil

from nova import exception
from nova.i18n import _
from nova.virt.vmwareapi import vim_util
from nova.virt.vmwareapi import vm_util

LOG = logging.getLogger(__name__)


def _get_network_obj(session, network_objects, network_name):
    """Gets the network object for the requested network.

    The network object will be used when creating the VM configuration
    spec. The network object contains the relevant network details for
    the specific network type, for example, a distributed port group.

    The method will search for the network_name in the list of
    network_objects.

    :param session: vCenter soap session
    :param network_objects: group of networks
    :param network_name: the requested network
    :return: network object
    """

    network_obj = {}
    # network_objects is actually a RetrieveResult object from vSphere API call
    for obj_content in network_objects:
        # the propset attribute "need not be set" by returning API
        if not hasattr(obj_content, 'propSet'):
            continue
        prop_dict = vm_util.propset_dict(obj_content.propSet)
        network_refs = prop_dict.get('network')
        if network_refs:
            network_refs = network_refs.ManagedObjectReference
            for network in network_refs:
                # Get network properties
                if network._type == 'DistributedVirtualPortgroup':
                    props = session._call_method(vutil,
                                                 "get_object_property",
                                                 network,
                                                 "config")