import external from './externalModules.js';
import store from './store/index.js';
import addEnabledElement from './store/internals/addEnabledElement.js';
import removeEnabledElement from './store/internals/removeEnabledElement.js';
import windowResizeHandler from './eventListeners/windowResizeHandler.js';

/**
 * Merges the provided configuration with default values and returns a
 * configured CornerstoneTools instance.
 * @export @public @method
 * @name init
 *
 * @param {object} configuration
 * @returns {object} A configured CornerstoneTools instance with top level API members.
 */
export default function (configuration) {
  _addCornerstoneEventListeners();
  _initModules();
  windowResizeHandler.enable();

  // Apply global configuration
  store.modules.globalConfiguration.state = Object.assign(
    {},
    store.modules.globalConfiguration.state,
    configuration
  );
}

/**
 * Wires up event listeners for the Cornerstone#ElementDisabled and
 * Cornerstone#ElementEnabled events.
 * @private @method
 */
function _addCornerstoneEventListeners () {
  const cornerstone = external.cornerstone;
  const elementEnabledEvent = cornerstone.EVENTS.ELEMENT_ENABLED;
  const elementDisabledEvent = cornerstone.EVENTS.ELEMENT_DISABLED;

  cornerstone.events.addEventListener(elementEnabledEvent, addEnabledElement);
  cornerstone.events.addEventListener(
    elementDisabledEvent,
    removeEnabledElement
  );
}

/*
 * TODO: This could cause issues if the module was already initialized for
 * the store. As there's nothing stopping implementers from calling `init`
 * multiple times. Modules should self-check if they have already been
 * registered to prevent issues.
 */

/**
 * Iterate over our store's modules. If the module has an `onRegisterCallback`
 * call it. This hook can be used to setup any global store requirements per
 * module.
 * @private @method
 */
function _initModules () {
  const modules = store.modules;

  Object.keys(modules).forEach(function (key) {
    if (typeof modules[key].onRegisterCallback === 'function') {
      modules[key].onRegisterCallback();
    }
  });
}

@@ -1059,24 +1059,112 @@
 teners () %7B%0A
+  // Clear any listeners that may already be set%0A  _removeCornerstoneEventListeners();%0A%0A
   const corn
@@ -1507,16 +1507,558 @@
   );%0A%7D%0A%0A
+/**%0A * Removes event listeners for the Cornerstone#ElementDisabled and%0A * Cornerstone#ElementEnabled events.%0A * @private @method%0A */%0Afunction _removeCornerstoneEventListeners () %7B%0A  const cornerstone = external.cornerstone;%0A  const elementEnabledEvent = cornerstone.EVENTS.ELEMENT_ENABLED;%0A  const elementDisabledEvent = cornerstone.EVENTS.ELEMENT_DISABLED;%0A%0A  cornerstone.events.removeEventListener(elementEnabledEvent, addEnabledElement);%0A  cornerstone.events.removeEventListener(%0A    elementDisabledEvent,%0A    removeEnabledElement%0A  );%0A%7D%0A%0A
 /*%0A * TO

Remove any lingering listeners that may still be on the instance before we init