# Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
#
# This is based on the following
#     https://github.com/osrg/gobgp/test/lib/quagga.py
#
# 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.

from __future__ import absolute_import

import logging

import netaddr

from . import docker_base as base

LOG = logging.getLogger(__name__)


class QuaggaBGPContainer(base.BGPContainer):

    WAIT_FOR_BOOT = 1
    SHARED_VOLUME = '/etc/quagga'

    def __init__(self, name, asn, router_id, ctn_image_name, zebra=False):
        super(QuaggaBGPContainer, self).__init__(name, asn, router_id,
                                                 ctn_image_name)
        self.shared_volumes.append((self.config_dir, self.SHARED_VOLUME))
        self.zebra = zebra
        self._create_config_debian()

    def run(self, wait=False):
        w_time = super(QuaggaBGPContainer,
                       self).run(wait=wait, w_time=self.WAIT_FOR_BOOT)
        return w_time

    def get_global_rib(self, prefix='', rf='ipv4'):
        rib = []
        if prefix != '':
            return self.get_global_rib_with_prefix(prefix, rf)

        out = self.vtysh('show bgp {0} unicast'.format(rf), config=False)
        if out.startswith('No BGP network exists'):
            return rib

        read_next = False

        for line in out.split('\n'):
            if line[:2] == '*>':
                line = line[2:]
                ibgp = False
                if line[0] == 'i':
                    line = line[1:]
                    ibgp = True
            elif not read_next:
                continue

            elems = line.split()

            if len(elems) == 1:
                read_next = True
                prefix = elems[0]
                continue
            elif read_next:
                nexthop = elems[0]
            else:
                prefix = elems[0]
                nexthop = elems[1]
            read_next = False

            rib.append({'prefix': prefix, 'nexthop': nexthop,
                        'ibgp': ibgp})

        return rib

    def get_global_rib_with_prefix(self, prefix, rf):
        rib = []

        lines = [line.strip() for line in self.vtysh(
            'show bgp {0} unicast {1}'.format(rf, prefix),
            config=False).split('\n')]

        if lines[0] == '% Network not in table':