const path = require('path');
const webpack = require('webpack');

/**
 * @param Encore
 * @param [options={}] - aliases and sassFilesToOverride parameters availables
 * @return {}
 */
module.exports = (Encore, options = {}) => {
  Encore
    .setOutputPath('public/build/dedi')
    .setPublicPath('/build/dedi')
    .addEntry('dedi', `${__dirname}/assets`)
    .addEntry('collection_form', `${__dirname}/assets/js/collection_form`)
    .addAliases(Object.assign({
      vendor: path.resolve(__dirname, 'node_modules'),
      fonts: path.resolve(__dirname, 'assets/fonts'),
      media: path.resolve(__dirname, 'assets/media'),
    }, options.aliases || {}))
    .addPlugin(new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      popper: 'popper.js',
      lightbox: 'lightbox2/dist/js/lightbox.min',
      bootstrap: 'bootstrap/dist/js/bootstrap.min',
    }))
    .copyFiles({
      from: `${__dirname}/assets/media`,
      to: 'images/[path][name].[ext]',
    })
    .copyFiles({
      from: `${__dirname}/assets/fonts`,
      to: 'fonts/[path][name].[ext]',
    })
    .disableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    /** Override sass file if option exists, else keep dedi theme file **/
    .enableSassLoader((opt) => {
      opt.sassOptions = Object.assign(opt.sassOptions || {}, {
        importer: (url, prev, done) => {
          if (options.sassFilesToOverride && options.sassFilesToOverride[url]) {
            return done({ file: options.sassFilesToOverride[url] });
          }

          done();
        }
      });

      return opt;
    })
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction());

  const config = Encore.getWebpackConfig();
  config.name = 'dedi';

  return config;
};
