import time
import socket
from pika.exceptions import AMQPError
from onapp.messaging.connection import Connection
import onapp.lib.log as log

class Consumer:
    def __init__(self, on_message, reconnect_period = 60):
        self.on_message = on_message
        self.reconnect_period = reconnect_period

    def start(self):
        while True:
            try:
                connection = None
                connection = Connection()
                channel = connection.open_channel()
                queue = connection.queue
                tag = "cdn_%s" % queue

                log.debug('Consuming X:%s Q:%s' % (connection.exchange, queue))

                channel.basic_consume(self.on_message, queue=queue, consumer_tag=tag)

                try:
                    channel.start_consuming()
                except KeyboardInterrupt:
                    channel.stop_consuming()
                    log.info('Consumption cancelled')

                self.__close_connection_safely(connection)
                break
            except (AMQPError, socket.error) as error:
                self.__close_connection_safely(connection)
                log.error(error)
                log.error('Reconnect in %s seconds' % self.reconnect_period)
                time.sleep(self.reconnect_period)

    def __close_connection_safely(self, connection):
        try:
            connection.close()
        except:
            pass
