#!/usr/bin/python3.6 -s
# GPL. (C) 2017 Paolo Patruno.

# This program is free software; you can redistribute it and/or modify 
# it under the terms of the GNU General Public License as published by 
# the Free Software Foundation; either version 2 of the License, or 
# (at your option) any later version. 
# 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
# GNU General Public License for more details. 
# 
# You should have received a copy of the GNU General Public License 
# along with this program; if not, write to the Free Software 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
# 


import os,sys
import pika
import logging

import rmap.settings

user=rmap.settings.amqpuser
password=rmap.settings.amqppassword
host="localhost"
#exchange=rmap.settings.exchangecomposereportd
exchange=sys.argv[1]
inputfile=sys.argv[2]
routing_key=exchange

def main():

    import logging,logging.handlers

    # configure the logger
    formatter=logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
    handler = logging.StreamHandler(sys.stdout)
    #handler = logging.handlers.RotatingFileHandler("/tmp/toamqp.log", maxBytes=5000000, backupCount=10)
    handler.setFormatter(formatter)
    
    # Add the log message handler to the root logger
    logging.getLogger().addHandler(handler)
    logging.getLogger().setLevel(logging.ERROR)

    logging.debug('started new process: %s' % sys.argv[0])
    logging.debug('send to exchange: %s' % exchange)
    
    try:
        # Legge un file.
        logging.debug('Read file: %s' % inputfile)

        with open (inputfile,"rb") as infile:
            totalbody = infile.read()

        logging.debug('message: %s' % totalbody)
                        
        credentials=pika.PlainCredentials(user, password)
        properties=pika.BasicProperties(
            user_id= user,
            delivery_mode = 2, # persistent
        )

        # connection_attempts (int) - Maximum number of retry attempts
        # retry_delay (int|float) - Time to wait in seconds, before the next
        # socket_timeout (int|float) - Use for high latency networks
                        
        connection = pika.BlockingConnection(pika.ConnectionParameters(
            host=host,credentials=credentials,
            connection_attempts=3,
            retry_delay=5,
            socket_timeout=3.))

        channel = connection.channel()
            
        #channel.queue_declare(queue=queue)
            
        # Turn on delivery confirmations
        channel.confirm_delivery()
            
        if channel.basic_publish(exchange=exchange,
                                 routing_key=routing_key,
                                 body=totalbody,
                                 properties=properties):
            logging.info('Message publish was confirmed')
        else:
            logging.info('Message could not be confirmed')
            
        logging.info(" [x] message Sent")
        connection.close()
        logging.info("Connection closed")
        return 0

    except:
        logging.error("There were some errors executing toamqp")    	
        return 0

if __name__ == '__main__':

    # (this code was run as script)
    
    sys.exit(main())
