/* globals requirejs */
import $ from 'jquery';
import RSVP from 'rsvp';
import injectScript from 'web-client/utilities/inject-script';

export function setupFeatures(features = []) {
  let knownModules = {};
  let featureInjector = [];
  let originalFeatures = window.features;

  if (features.length) {
    knownModules = Object.keys(requirejs.entries);
    featureInjector = features.map((feature) => {
      return injectScript(`${feature}.js`);
    });
  }

  return {
    features,
    originalFeatures,
    originalModules: knownModules,
    featureInjector: RSVP.all(featureInjector)
  };
}

// setupFeaturesObject is the object returned from `setupFeatures`
export function teardownFeatures(setupFeaturesObject) {
  return setupFeaturesObject.featureInjector
    .then((scripts) => {
      if (!setupFeaturesObject.features.length) { return; }

      teardownFeatureModules(setupFeaturesObject.originalModules);
      removeScriptTags(scripts);

      // Reset the features global to previous value.
      window.features = setupFeaturesObject.originalFeatures;
    });
}

let teardownFeatureModules = function(originalModules) {
  let currentModules = Object.keys(requirejs.entries);

  for (let i = 0; i < currentModules.length; ++i) {
    let key = currentModules[i];
    if (originalModules.indexOf(key) === -1) {
      requirejs.unsee(key);
      delete requirejs.entries[key];
    }
  }
};

let removeScriptTags = function(scripts) {
  scripts.forEach((script) => {
    return $(script).remove();
  });
};
