# Copyright (c) 2011 - 2017, Intel Corporation.
#
# 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.

"""``BGP.py``

``IxNetwork BGP protocol emulation functionality``

Note:
    TCL procedures::

        ::ixia::emulation_bgp_config
        ::ixia::emulation_bgp_control
        ::ixia::emulation_bgp_info
        ::ixia::emulation_bgp_route_config


"""

import copy


class BGP(object):
    """IxNet BGP configuration wrapper.

    """

    def __init__(self, ixia):
        """BGP class initialization.

        Args:
            ixia(IxiaHLTMixin):  Ixia traffic generator

        """
        self.ixia = ixia
        self.bgp_dict = {}

    def configure_neighbour(self, port, *args, **kwargs):
        """Configure BGP neighbors.

        Args:
            port(tuple(int)):  TG port in format tuple(chassisID, cardId, portId)

        Raises:
            AssertionError:  error in executing tcl code

        Returns:
            dict: Neighbour handler names

        Note:
            See description of keyword arguments in ixia_bgp_api.tcl

            Full path: /opt/ixos/lib/hltapi/library/ixia_bgp_api.tcl

        """
        kwargs['port_handle'] = "/".join(map(str, port))
        self.ixia.ixia_emulation_bgp_config(*args, **kwargs)
        assert self.ixia.check_return_code() == ""

        _port = "_".join(map(str, port))
        cfg_name = "bgp_routers_status_{0}".format(_port)
        if port not in self.bgp_dict:
            self.bgp_dict[port] = {}
        self.bgp_dict[port]['cfg_name'] = cfg_name
        if "n_handler" not in self.bgp_dict:
            self.bgp_dict[port]['n_handler'] = {}

        self.ixia.set_var(**{cfg_name: "$return_code"})

        # Create bgp neighbors handles list
        _rlist = self.ixia.tcl("keylget {0} handles".format(cfg_name))
        _rlist = _rlist.split(" ")
        for item in _rlist:
            # item example: 'ixNet::OBJ-/vport:1/protocols/bgp/neighborRange:1'
            pos = item.rfind(":")
            _id = item[pos + 1:]
            _index = _rlist.index(item)
            self.bgp_dict[port]['n_handler'][_id] = "bgp_neighbour_{0}_{1}".format(_port, _id)
            self.ixia.set_var(**{self.bgp_dict[port]['n_handler'][_id]: "[lindex [keylget {0} handles] {1}]".format(cfg_name, _index)})

        return self.bgp_dict[port]['n_handler'].copy()

    def control(self, *args, **kwargs):
        """Turning BGP on/off, enabling statistics.