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`)
    .addEntry('design-system', `${__dirname}/assets/js/design-system`)
    .addStyleEntry('styleguide', `${__dirname}/assets/scss/pages/styleguide.scss`)
    .addStyleEntry('homepage', `${__dirname}/assets/scss/pages/homepage.scss`)
    .addStyleEntry('account', `${__dirname}/assets/scss/pages/account.scss`)
    .addStyleEntry('shop', `${__dirname}/assets/scss/pages/shop.scss`)
    .addStyleEntry('process', `${__dirname}/assets/scss/pages/process.scss`)
    .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) {
            // Get root scss
            const rootUrl = url.replace('../', '');

            if (options.sassFilesToOverride[rootUrl]) {
              return done({ file: options.sassFilesToOverride[rootUrl] });
            }
          }

          done();
        }
      });

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

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

  return config;
};
