var amqp = require('./amqp-layer')();
var logger = require('../helpers/logger')(true);

var channel, config;
var connected = connecting = false;
var reqQueue = [];

var consume = function(_queue, _callback) {
  _queue += (process.env.LOCAL_QUEUE ? process.env.LOCAL_QUEUE : '');

  if (!connected) {
    reqQueue.push(function () {
      consume(_queue, _callback);
    });

    if (!connecting) {
      connecting = true;

      amqp.connect(config.amqpUrl)
      .then(function (_channel) {
        logger.log('info', '[AMQP] Consumer is now connected and ready to consume messages');

        channel = _channel;
        connected = true;

        while (reqQueue.length > 0) {
          reqQueue.pop()();
        }
      });
    }
  } else {
    var done_callback = function (_msg) {
      logger.log('info', '[AMQP] Consumer received msg:', _msg.content.toString());

      return Promise.resolve(_msg.content.toString())
      .then(_callback)
      .then(function (_response) {
        channel.ack(_msg);
      })
      .catch(function (err) {
        // if (err) channel.nack();
      });
    };

    channel.assertQueue(_queue, { durable: true })
    .then(function () {
      channel.prefetch(1);
      channel.consume(_queue, done_callback, { noAck: false });
    });
  }
};

module.exports = function (_config) {
  config = _config;

  logger.enableDisableLog(config.isLogEnabled);

  return {
    consume: consume
  };
};

var amqp = require('./amqp-layer')();
var logger = require('../helpers/logger')(true);

var channel, config;
var connected = connecting = false;
var reqQueue = [];

var consume = function(_queue, _callback) {
  _queue += (process.env.LOCAL_QUEUE ? process.env.LOCAL_QUEUE : '');

  if (!connected) {
    reqQueue.push(function () {
      consume(_queue, _callback);
    });

    if (!connecting) {
      connecting = true;

      amqp.connect(config.amqpUrl)
      .then(function (_channel) {
        logger.log('info', '[AMQP] Consumer is now connected and ready to consume messages');

        channel = _channel;
        connected = true;

        while (reqQueue.length > 0) {
          reqQueue.pop()();
        }
      });
    }
  } else {
    var done_callback = function (_msg) {
      logger.log('info', '[AMQP] Consumer received msg:', _msg.content.toString());

      return Promise.resolve(_msg.content.toString())
      .then(_callback)
      .then(function (_response) {
        channel.ack(_msg);
      })
      .catch(function (err) {
        // if (err) channel.nack();
      });
    };

    channel.assertQueue(_queue, { durable: true })
    .then(function () {
      channel.prefetch(config.prefetch);
      channel.consume(_queue, done_callback, { noAck: false });
    });
  }
};

module.exports = function (_config) {
  config = _config;

  logger.enableDisableLog(config.isLogEnabled);

  return {
    consume: consume
  };
};

Use config.prefetch