var Insights, async, getJobStats, getJobStatsApps, main, normalize, parse;

Insights = require('node-insights');

async = require('async');

getJobStats = function(options, app, callback) {
  var insights, limit, q;
  insights = new Insights(options);
  if (!app) {
    return callback(new Error('Missing app name'));
  }
  limit = 100; // maximum number of role supported
  q = `SELECT average(duration), stddev(duration), percentile(duration, 90) FROM MsgfloJobCompleted FACET role SINCE ${options.since} ago WHERE outport != 'error' AND appName = '${app}' LIMIT ${limit}`;
  return insights.query(q, function(err, body) {
    var facet, i, j, len, len1, out, ref, ref1, ref2, res, results;
    if (err) {
      return callback(err);
    }
    if (!((ref = body.facets) != null ? ref.length : void 0)) {
      return callback(new Error("newrelic: No facets was returned in query"));
    }
    results = {};
    ref1 = body.facets;
    for (i = 0, len = ref1.length; i < len; i++) {
      facet = ref1[i];
      out = results[facet.name] = {};
      ref2 = facet.results;
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        res = ref2[j];
        if (res['average'] != null) {
          out['average'] = res['average'] / 1000;
        }
        if (res['standardDeviation'] != null) {
          out['stddev'] = res['standardDeviation'] / 1000;
        }
        if (res['percentile'] != null) {
          out['percentile'] = res['percentile'] / 1000;
        }
      }
    }
    return callback(null, results);
  });
};

getJobStatsApps = function(options, apps, callback) {
  var getStats;
  getStats = function(app, cb) {
    return getJobStats(options, app, cb);
  };
  return async.map(apps, getStats, function(err, resultList) {
    var i, k, len, obj, res, v;
    if (err) {
      return callback(err);
    }
    res = {};
    for (i = 0, len = resultList.length; i < len; i++) {
      obj = resultList[i];
      for (k in obj) {
        v = obj[k];
        res[k] = v;
      }
    }
    return callback(null, res);
  });
};

parse = function(args) {
  var addApp, program;
  addApp = function(app, list) {
    list.push(app);
    return list;
  };
  program = require('commander');
  return program.option('--query-key <hostname>', 'Query Key to access New Relic Insights API', String, '').option('--account-id <port>', 'Account ID used to access New Relic Insights API', String, '').option('--app <app>', 'App name in New Relic. Can be specified multiple times', addApp, []).option('--since <datetime>', 'Timeperiod to extract metrics for', String, '1 week').parse(args);
};

normalize = function(options) {
  if (!options.accountId) {
    options.accountId = process.env.NEW_RELIC_ACCOUNT_ID;
  }
  if (!options.queryKey) {
    options.queryKey = process.env.NEW_RELIC_QUERY_KEY;
  }
  if (typeof options.app === 'string') {
    options.app = [options.app];
  }
  return options;
};

exports.main = main = function() {
  var options;
  options = parse(process.argv);
  options = normalize(options);
  return getJobStatsApps(options, options.app, function(err, results) {
    if (err) {
      throw err;
    }
    return console.log(JSON.stringify(results, null, 2));
  });
};

if (!module.parent) {
  main();
}
