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

module.exports = function(webpackConfig, env) {

  webpackConfig.plugins.shift();

  webpackConfig.babel.plugins.push('transform-runtime');

  // Support hmr
  if (env === 'development') {
    webpackConfig.devtool = '#eval';
    webpackConfig.babel.plugins.push(['dva-hmr', {
      entries: [
        // './src/public.js',
      ],
    }]);
  } else {
    webpackConfig.babel.plugins.push('dev-expression');
  }

  // Support CSS Modules
  // Parse all less files as css module.
  webpackConfig.module.loaders.forEach(function(loader, index) {
    var test = loader.test;
    var testString = test.toString() + '';
    if (typeof test === 'function' && testString.indexOf('\\.less$') > -1) {
      loader.include = /node_modules/;
      loader.test = /\.less$/;
    }
    if (testString === '/\\.module\\.less$/') {
      loader.exclude = /node_modules/;
      loader.test = /\.less$/;
    }
    if (typeof test === 'function' && testString.indexOf('\\.css$') > -1) {
      loader.include = /node_modules/;
      loader.test = /\.css$/;
    }
    if (testString === '/\\.module\\.css$/') {
      loader.exclude = /node_modules/;
      loader.test = /\.css$/;
    }
    switch(testString){
      case '/\\.(png|jpg|jpeg|gif)(\\?v=\\d+\\.\\d+\\.\\d+)?$/i':
        loader.loader = 'url?limit=10000' + (env === 'development' ? '&name=[path][name].[ext]' : '&name=images/[hash].[ext]');
        break;
      case '/\\.woff(\\?v=\\d+\\.\\d+\\.\\d+)?$/':
        loader.test = /\.woff((\?v=\d+\.\d+\.\d+)|(\?t=\d+))?$/i;
        loader.loader = 'url?limit=2048&minetype=application/font-woff' + (env === 'development' ? '': '&name=fonts/[hash].[ext]');
        break;
      case '/\\.woff2(\\?v=\\d+\\.\\d+\\.\\d+)?$/':
        loader.test = /\.woff2((\?v=\d+\.\d+\.\d+)|(\?t=\d+))?$/i;
        loader.loader = 'url?limit=2048&minetype=application/font-woff' + (env === 'development' ? '': '&name=fonts/[hash].[ext]');
        break;
      case '/\\.ttf(\\?v=\\d+\\.\\d+\\.\\d+)?$/':
        loader.test = /\.ttf((\?v=\d+\.\d+\.\d+)|(\?t=\d+))?$/i;
        loader.loader = 'url?limit=2048&minetype=application/octet-stream' + (env === 'development' ? '': '&name=fonts/[hash].[ext]');
        break;
      case '/\\.eot(\\?v=\\d+\\.\\d+\\.\\d+)?$/':
        loader.test = /\.eot((\?v=\d+\.\d+\.\d+)|(\?t=\d+))?(\#iefix)?$/i;
        loader.loader = 'file' +  (env === 'development' ? '': '?name=fonts/[hash].[ext]');
        break;
      case '/\\.svg(\\?v=\\d+\\.\\d+\\.\\d+)?$/':
        loader.test = /\.svg((\?v=\d+\.\d+\.\d+)|(\?t=\d+))?(\#iconfont)?$/i;
        loader.loader = 'url?limit=2048&minetype=image/svg+xml' + (env === 'development' ? '': '&name=images/[hash].[ext]');
        break;
      case '/\\.html?$/':
        loader.loader = 'file?name=[name].[ext]!extract!html'
        break;
    }
  });

  webpackConfig.externals= {
    jquery: 'window.$'
  };

  return webpackConfig;
};
