'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

exports['default'] = updateWebpackConfig;

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path = require('path');

var _webpack = require('webpack');

var _webpack2 = _interopRequireDefault(_webpack);

var _extractTextWebpackPlugin = require('extract-text-webpack-plugin');

var _extractTextWebpackPlugin2 = _interopRequireDefault(_extractTextWebpackPlugin);

var _htmlWebpackPlugin = require('html-webpack-plugin');

var _htmlWebpackPlugin2 = _interopRequireDefault(_htmlWebpackPlugin);

var _context = require('../bin/common/context');

var _context2 = _interopRequireDefault(_context);

var _getStyleLoadersConfig = require('./getStyleLoadersConfig');

var _getStyleLoadersConfig2 = _interopRequireDefault(_getStyleLoadersConfig);

var _getEnterPointsConfig = require('./getEnterPointsConfig');

var _getEnterPointsConfig2 = _interopRequireDefault(_getEnterPointsConfig);

var _getWebpackCommonConfig = require('./getWebpackCommonConfig');

var _getWebpackCommonConfig2 = _interopRequireDefault(_getWebpackCommonConfig);

var _getDefaultTheme = require('./getDefaultTheme');

var _getDefaultTheme2 = _interopRequireDefault(_getDefaultTheme);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var choerodonLib = (0, _path.join)(__dirname, '..');

function getFilePath(file) {
  var isDev = _context2['default'].isDev;

  var filePath = (0, _path.join)(process.cwd(), file);
  if (_fs2['default'].existsSync(filePath)) {
    return filePath;
  } else if (isDev) {
    return (0, _path.join)(process.cwd(), 'src', file);
  } else {
    return (0, _path.join)(__dirname, '..', file);
  }
}

function updateWebpackConfig(mode, env) {
  var webpackConfig = (0, _getWebpackCommonConfig2['default'])(mode, env);
  var choerodonConfig = _context2['default'].choerodonConfig;
  var theme = choerodonConfig.theme,
      output = choerodonConfig.output,
      root = choerodonConfig.root,
      enterPoints = choerodonConfig.enterPoints,
      server = choerodonConfig.server,
      webSocketServer = choerodonConfig.webSocketServer,
      local = choerodonConfig.local,
      postcssConfig = choerodonConfig.postcssConfig,
      entryName = choerodonConfig.entryName,
      titlename = choerodonConfig.titlename,
      htmlTemplate = choerodonConfig.htmlTemplate,
      favicon = choerodonConfig.favicon;

  var styleLoadersConfig = (0, _getStyleLoadersConfig2['default'])(postcssConfig, {
    sourceMap: mode === 'start',
    modifyVars: (0, _extends3['default'])({}, (0, _getDefaultTheme2['default'])(env), theme)
  });

  var defaultEnterPoints = void 0;
  webpackConfig.entry = {};
  if (mode === 'start') {
    webpackConfig.output.publicPath = '/';
    webpackConfig.devtool = 'cheap-module-eval-source-map';
    webpackConfig.watch = true;
    styleLoadersConfig.forEach(function (config) {
      webpackConfig.module.rules.push({
        test: config.test,
        use: ['style-loader'].concat((0, _toConsumableArray3['default'])(config.use))
      });
    });
    defaultEnterPoints = {
      API_HOST: server,
      AUTH_HOST: server,
      LOCAL: local,
      VERSION: '本地',
      TITLE_NAME: titlename,
      WEBSOCKET_SERVER: webSocketServer
    };
  } else if (mode === 'build') {
    webpackConfig.output.publicPath = root;
    webpackConfig.output.path = (0, _path.join)(process.cwd(), 'src', 'main', 'resources', 'lib', output);
    styleLoadersConfig.forEach(function (config) {
      webpackConfig.module.rules.push({
        test: config.test,
        use: _extractTextWebpackPlugin2['default'].extract({
          use: config.use
        })
      });
    });
    // defaultEnterPoints = getEnterPointsConfig();
    defaultEnterPoints = {
      API_HOST: server,
      AUTH_HOST: server,
      LOCAL: local,
      VERSION: '本地',
      TITLE_NAME: titlename,
      WEBSOCKET_SERVER: ''
    };
  }
  /* eslint-enable no-param-reassign */
  var mergedEnterPoints = (0, _extends3['default'])({
    NODE_ENV: env
  }, defaultEnterPoints, enterPoints(mode, env));
  var defines = Object.keys(mergedEnterPoints).reduce(function (obj, key) {
    obj['process.env.' + key] = JSON.stringify(process.env[key] || mergedEnterPoints[key]);
    return obj;
  }, {});
  var customizedWebpackConfig = choerodonConfig.webpackConfig(webpackConfig, _webpack2['default']);

  if (customizedWebpackConfig.entry[entryName]) {
    throw new Error('Should not set `webpackConfig.entry.' + entryName + '`!');
  }
  var entryPath = (0, _path.join)(choerodonLib, '..', 'tmp', 'entry.' + entryName + '.js');
  var entryWithoutSiderPath = (0, _path.join)(choerodonLib, '..', 'tmp', 'entry.withoutsider.js');
  customizedWebpackConfig.entry[entryName] = entryPath;
  customizedWebpackConfig.entry.withoutsider = entryWithoutSiderPath;
  customizedWebpackConfig.plugins.push(new _webpack2['default'].DefinePlugin(defines), new _htmlWebpackPlugin2['default']({
    title: process.env.TITLE_NAME || titlename,
    template: getFilePath(htmlTemplate),
    // fileName: 'index.html',
    inject: true,
    chunks: ['vendor', entryName],
    favicon: getFilePath(favicon),
    minify: {
      html5: true,
      collapseWhitespace: true,
      removeComments: true,
      removeTagWhitespace: true,
      removeEmptyAttributes: true,
      removeStyleLinkTypeAttributes: true
    }
  }), new _htmlWebpackPlugin2['default']({
    title: process.env.TITLE_NAME || titlename,
    template: getFilePath(htmlTemplate),
    chunks: ['vendor', 'withoutsider'],
    filename: 'withoutsider.html',
    inject: true,
    favicon: getFilePath(favicon),
    minify: {
      html5: true,
      collapseWhitespace: true,
      removeComments: true,
      removeTagWhitespace: true,
      removeEmptyAttributes: true,
      removeStyleLinkTypeAttributes: true
    }
  }));
  return customizedWebpackConfig;
}