/*
 * @Author: miaokefu@duiba.com.cn 
 * @Date: 2018-08-29 20:48:34 
 * @desc 在entry.html同级生成自定义的html代码块
 */ 

 // TODO 打包时运行git log写入最近一次提交记录
const pluginName = 'WebpackCustomOutputPlugin';
class CustomOutputPlugin {
  constructor(opts) {
    let defaultOpts = {
      removeArr: [] // 需要去除的字符串
    };
    this.options = Object.assign({}, defaultOpts, opts);
  }

  apply(compiler) {
    if (compiler.hooks) {
      // webpack 4 support
      compiler.hooks.compilation.tap(pluginName, compilation => {
        compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tapAsync(
          pluginName,
          (htmlPluginData, callback) => {
            this.getCustomBodyContent(compilation, htmlPluginData, callback);
          }
        );
      });
    } else {
      // Hook into the html-webpack-plugin-after-html-processing
      compiler.plugin('compilation', compilation => {
        compilation.plugin(
          'html-webpack-plugin-after-html-processing',
          (htmlPluginData, callback) => {
            this.getCustomBodyContent(compilation, htmlPluginData, callback);
          }
        );
      });
    }
  }

  getCustomBodyContent(compilation, data, callback) {
    let dir = this.getFileDir(data.outputName);
    let body = this.getHtmlBody(data.html);
    let cssTags = '';

    cssTags = data.assets.css.reduce((accumulator, currentValue) => {
      return accumulator + this.getCssTag(currentValue) + '\n';
    }, cssTags);

    body = cssTags + body;

    this.options.removeArr.forEach(item => {
      let regExp = new RegExp(item, 'g');
      body = body.replace(regExp, '');
    });
    compilation.assets[dir + 'output.html'] = {
      source: function() {
        return body;
      },
      size: function() {
        return body.length;
      }
    };
    callback(null, data);
  }

  getFileDir(filePath) {
    let lastIndex = filePath.lastIndexOf('/');
    return filePath.substring(0, lastIndex + 1); // 加最后/
  }
  getHtmlBody(str) {
    let regExp = /<body[\s]*>([\s\S]*)<\/body>/;

    let body = '';
    let matchObj = str.match(regExp);
    if (matchObj && matchObj[1]) {
      body = matchObj[1];
    }
    return body;
  }

  getCssTag(url) {
    return `<link href="${url}" rel="stylesheet">`;
  }
}

module.exports = CustomOutputPlugin;
