#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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 unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

import ast
from time import sleep
from subprocess import PIPE, STDOUT

from system_test import TestCase, Qdrouterd, main_module, TIMEOUT, Process
from system_test import AsyncTestReceiver
from system_test import unittest
from proton import Message, Timeout
from proton.reactor import AtMostOnce, AtLeastOnce
from proton.utils import BlockingConnection, SendException

#TIMEOUT=5
_EXCHANGE_TYPE = "org.apache.qpid.dispatch.router.config.exchange"
_BINDING_TYPE  = "org.apache.qpid.dispatch.router.config.binding"


class ExchangeBindingsTest(TestCase):
    """
    Tests the exchange/bindings of the dispatch router.
    """
    def _create_router(self, name, config):

        config = [
            ('router',   {'mode': 'standalone', 'id': 'QDR.%s'%name}),
            ('listener', {'role': 'normal', 'host': '0.0.0.0',
                          'port': self.tester.get_port(),
                          'saslMechanisms':'ANONYMOUS'})
            ] + config
        return self.tester.qdrouterd(name, Qdrouterd.Config(config))

    def run_qdmanage(self, router, cmd, input=None, expect=Process.EXIT_OK):
        p = self.popen(
            ['qdmanage'] + cmd.split(' ')
            + ['--bus', router.addresses[0], '--indent=-1', '--timeout', str(TIMEOUT)],
            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
            universal_newlines=True)
        out = p.communicate(input)[0]
        try:
            p.teardown()
        except Exception as e:
            raise Exception("%s\n%s" % (e, out))