// Licensed Materials - Property of IBM
// 5725-I43 (C) Copyright IBM Corp. 2015. All Rights Reserved.
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

'use strict';

/*
aggregateExtensions = {
	point: [
		{
            <key value pairs specified in the extension object>,
            export: <exported object>
        }
	]
}
*/
var aggregateExtensions;

var loadExtensions = function(basePath, debug) {
  var glob = require('glob');
  var path = require('path');

  aggregateExtensions = {};

  // get all the package.json files
  var packages = glob.sync(path.join(basePath, '*/package.json'));

  // for each of those, read them, and find their extensions
  packages.forEach(function(pkgFile) {
    var pluginDir = path.dirname(pkgFile);
    //console.log('pluginDir: ' + pluginDir);

    var pkg = require(pkgFile);
    if (pkg.extensions) {

      pkg.extensions.forEach(function(descriptor) {
        //console.log('Found extensions to: ' + extensionPoint);

        // the object to be given to extension readers
        var extension = {};

        // merge in all the values except 'point' and 'exports', allowing
        // extensions to pass metadata to the reader
        for (var key in descriptor) {
          if (key !== 'point' && key !== 'exports') {
            extension[key] = descriptor[key];
          }
        }

        // load the exported file lazily through the export getter function
        Object.defineProperty(extension,
          'export', {
            get: function() {
              return require(path.join(pluginDir, descriptor.exports));
            }
          });

        if (!aggregateExtensions[descriptor.point]) {
          aggregateExtensions[descriptor.point] = [];
        }

        if (debug) {
          extension._path = pkgFile;
        }

        aggregateExtensions[descriptor.point].push(extension);
      });
    }
  });
};

module.exports = function(basePath, extensionPoint) {
  // TODO this caching system is actually broken because it doesn't cache different
  // basePath's separately. For now, just load every time.
  // if(!aggregateExtensions) {
  loadExtensions(basePath);
  // }

  return aggregateExtensions[extensionPoint];
};

/**
 * internal API used for debugging
 */
module.exports._getAllExtensions = function(basePath) {
  loadExtensions(basePath, true);
  return aggregateExtensions;
};
