'use strict';

var index = require('../../core/es/index.js');
var mime = require('../../core/es/utils/mime.js');

function configure(configuration) {
  let jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : index.default;
  const jimpConfig = {
    hasAlpha: {},
    encoders: {},
    decoders: {},
    class: {},
    constants: {}
  };
  function addToConfig(newConfig) {
    Object.entries(newConfig).forEach(_ref => {
      let [key, value] = _ref;
      jimpConfig[key] = {
        ...jimpConfig[key],
        ...value
      };
    });
  }
  function addImageType(typeModule) {
    const type = typeModule();
    if (Array.isArray(type.mime)) {
      mime.addType(...type.mime);
    } else {
      Object.entries(type.mime).forEach(mimeType => mime.addType(...mimeType));
    }
    delete type.mime;
    addToConfig(type);
  }
  function addPlugin(pluginModule) {
    const plugin = pluginModule(index.jimpEvChange) || {};
    if (!plugin.class && !plugin.constants) {
      // Default to class function
      addToConfig({
        class: plugin
      });
    } else {
      addToConfig(plugin);
    }
  }
  if (configuration.types) {
    configuration.types.forEach(addImageType);
    jimpInstance.decoders = {
      ...jimpInstance.decoders,
      ...jimpConfig.decoders
    };
    jimpInstance.encoders = {
      ...jimpInstance.encoders,
      ...jimpConfig.encoders
    };
    jimpInstance.hasAlpha = {
      ...jimpInstance.hasAlpha,
      ...jimpConfig.hasAlpha
    };
  }
  if (configuration.plugins) {
    configuration.plugins.forEach(addPlugin);
  }
  index.addJimpMethods(jimpConfig.class, jimpInstance);
  index.addConstants(jimpConfig.constants, jimpInstance);
  return index.default;
}

module.exports = configure;
