#
# 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 absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import with_statement

import proton as _proton
import proton.handlers as _handlers
import proton.reactor as _reactor

from .common import *

_description = "Receive AMQP messages"

class ReceiveCommand(Command):
    def __init__(self, home_dir):
        super(ReceiveCommand, self).__init__(home_dir)

        self.parser.description = _description

        self.parser.add_argument("url", metavar="ADDRESS-URL", nargs="+",
                                 help="The location of a message source")
        self.parser.add_argument("-m", "--messages", metavar="COUNT",
                                 type=int, default=0,
                                 help="Receive COUNT messages; 0 means no limit")

        self.add_common_arguments()

        self.container = _reactor.Container(_ReceiveHandler(self))

    def init(self):
        super(ReceiveCommand, self).init()

        self.init_common_attributes()

        self.urls = self.args.url
        self.max_messages = self.args.messages

        self.container.container_id = self.id

    def run(self):
        self.container.run()

class _ReceiveHandler(_handlers.MessagingHandler):
    def __init__(self, command):
        super(_ReceiveHandler, self).__init__()

        self.command = command
        self.connections = set()
        self.receivers = set()
        self.count = 0

    def on_start(self, event):
        for url in self.command.urls:
            host, port, path = parse_address_url(url)
            domain = "{}:{}".format(host, port)

            connection = event.container.connect(domain, allowed_mechs=b"ANONYMOUS")
            receiver = event.container.create_receiver(connection, path)

            self.connections.add(connection)
            self.receivers.add(receiver)

    def on_connection_opened(self, event):
        assert event.connection in self.connections

        self.command.notice("Connected to container '{}'", event.connection.remote_container)

    def on_link_opened(self, event):
        assert event.link in self.receivers

        self.command.notice("Created receiver for source address '{}' on container '{}'",
                            event.link.source.address,
                            event.connection.remote_container)

    def on_message(self, event):
        self.count += 1

        if self.count == self.command.max_messages:
            return

        print(event.message.body)

        if self.command.verbose:
            self.command.notice("Received message '{}' from '{}' on '{}'",
                                event.message.body,
                                event.link.source.address,
                                event.connection.remote_container)

        if self.count == self.command.max_messages:
            self.connection.close()

@@ -1065,16 +1065,35 @@
 _reactor
+%0Aimport sys as _sys
 %0A%0Afrom .
@@ -1505,23 +1505,21 @@
 t(%22-
-m
+o
 %22, %22--
-messages
+output
 %22, m
@@ -1526,21 +1526,20 @@
 etavar=%22
-COUNT
+FILE
 %22,%0A     
@@ -1570,27 +1570,113 @@
     
-type=int, default=0
+help=%22Write message content to FILE%22)%0A        self.parser.add_argument(%22--max%22, metavar=%22COUNT%22, type=int
 ,%0A  
@@ -1712,23 +1712,36 @@
   help=%22
-R
+Stop after r
 eceiv
-e
+ing
  COUNT m
@@ -1751,26 +1751,8 @@
 ages
-; 0 means no limit
 %22)%0A%0A
@@ -2010,41 +2010,173 @@
 elf.
-max_messages = self.args.messages
+output_file = _sys.stdout%0A        self.max_count = self.args.max%0A%0A        if self.args.output is not None:%0A            self.output_file = open(self.args.output, %22w%22)
 %0A%0A  
@@ -2489,32 +2489,33 @@
 ceivers = set()%0A
+%0A
         self.cou
@@ -2511,21 +2511,33 @@
    self.
-count
+received_messages
  = 0%0A%0A  
@@ -3048,16 +3048,53 @@
 ctions%0A%0A
+        if self.command.verbose:%0A    
         
@@ -3143,16 +3143,48 @@
 r '%7B%7D'%22,
+%0A                               
  event.c
@@ -3548,46 +3548,33 @@
     
-self.count += 1%0A%0A        if self.count
+if self.received_messages
  == 
@@ -3586,32 +3586,29 @@
 command.max_
-messages
+count
 :%0A          
@@ -3629,32 +3629,139 @@
     
-print(event.message.body
+self.received_messages += 1%0A%0A        self.command.output_file.write(event.message.body)%0A        self.command.output_file.write(%22%5Cn%22
 )%0A%0A 
@@ -4062,21 +4062,33 @@
 if self.
-count
+received_messages
  == self
@@ -4104,35 +4104,118 @@
 max_
-messages:%0A            self.
+count:%0A            self.close()%0A%0A    def close(self):%0A        for connection in self.connections:%0A            
 conn

Add receiver output control; make things consistent with the sender