/*
 * Copyright (c) AppDynamics, Inc., and its affiliates
 * 2015
 * All Rights Reserved
 */
function tryRequire(moduleName) {
  var fullPath;
  try {
    fullPath = require.resolve(moduleName);
  }
  catch (e) {
    return undefined;
  }

  return require(fullPath);
}

function requireBinding() {
  var applicationPackage = 'appd_libagent';
  if (process.env.NODE_ENV === 'appd_test') {
    applicationPackage = 'appd_libagent_test';
  }
  var locations = ['./build/Debug/' + applicationPackage,
  './build/Release/' + applicationPackage];

  for (var i = 0; i < locations.length; i++) {
    var mod = tryRequire(locations[i]);
    if (mod)
      return mod;
  }

  // Try the last location without first
  // checking if that locations exists.
  return require('./appd_libagent');
}

function load(agent) {
  try {
    var mod = requireBinding();
    if (!mod) {
      throw new Error("Failed loading libagent extension.");
    }
    else {
      agent.logger.log("Loaded libagent extension.");
    }

    return mod;
  }
  catch (err) {
    agent.logger.error(err);
    agent.logger.message(
      "Compilation or installation of libagent extension failed and " +
      "precompiled package was not available or had no matching version. " +
      "Please try the latest version of \"appdynamics\". "
    );
  }
}

var native = requireBinding();
var libagent = require('./lib/libagent');
libagent.init(native);

module.exports = libagent;
module.exports.nativeModule = native;