"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _htmlWebpackPlugin = _interopRequireDefault(require("html-webpack-plugin"));

var _utils = require("../utils");

var _urlConcat = require("../utils/urlConcat");

var _path = _interopRequireDefault(require("path"));

var _webpackSources = require("webpack-sources");

var _hashUtils = require("./I18nSplitPlugin/utils/hashUtils");

var _getI18nFileUrlPathTemplate = require("./I18nSplitPlugin/utils/getI18nFileUrlPathTemplate");

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

let i18nObj = null;
const options = (0, _utils.getOptions)();

function newAssign(target, data) {
  return Object.assign({}, target, data);
}

const {
  i18n
} = options;

class I18NInjectIntoIndexPlugin {
  constructor(options) {
    this.isDevelopment = options.isDevelopment;
    this.i18nFileNameTemplate = options.i18nFileNameTemplate;
    this.publicPath = options.publicPath;
    this.templateLabel = options.templateLabel || '{{--user-locale}}';
    this.i18nManifestFileName = options.i18nManifestFileName;
    this.entryPointName = options.mainChunkName;
  }

  getI18nFileUrlPath(chunk, compilation) {
    const urlpath = (0, _getI18nFileUrlPathTemplate.getI18nFileUrlPathTemplate)(compilation, chunk, this.i18nFileNameTemplate, this.templateLabel);
    return (0, _urlConcat.urlConcat)(this.publicPath, urlpath);
  }

  getI18nManifest(compilation) {
    const i18nManifestFile = compilation.assets[this.i18nManifestFileName];

    if (!i18nManifestFile) {
      return {};
    }

    const manifest = JSON.parse(i18nManifestFile.source());
    return manifest;
  }

  injectI18nURLsToHTML(compilation) {
    _htmlWebpackPlugin.default.getHooks(compilation).beforeAssetTagGeneration.tapAsync('I18NInjectIntoIndexPlugin', (data, cb) => {
      const {
        assets
      } = data; // Manipulate the content

      const i18nManifest = this.getI18nManifest(compilation);
      const entryPoint = compilation.entrypoints.get(this.entryPointName);
      const i18nScriptURLs = entryPoint.chunks.filter(c => !!i18nManifest[c.id]).map(c => this.getI18nFileUrlPath(c, compilation)); // .map(url => getI18nScriptTagObj(url));
      // .join('');
      // Tell webpack to move on

      cb(null, newAssign(data, {
        assets: newAssign(assets, {
          js: i18nScriptURLs.concat(assets.js)
        })
      }));
    });
  }

  withI18nSpitHandling(compiler) {
    compiler.hooks.make.tap('I18NInjectIntoIndexPlugin', compilation => {
      // let cdns = Object.keys(this.publicPaths);
      if (!(0, _hashUtils.hasContentHash)(this.i18nFileNameTemplate)) {
        this.injectI18nURLsToHTML(compilation);
        return;
      }

      _htmlWebpackPlugin.default.getHooks(compilation).beforeEmit.tapAsync('I18NInjectIntoIndexPlugin', (data, cb) => {
        // Manipulate the content
        const i18nManifest = this.getI18nManifest(compilation);
        const entryPoint = compilation.entrypoints.get(this.entryPointName);
        const i18nAssets = (0, _hashUtils.getShortI18nAssets)(entryPoint.chunks, i18nManifest, this.publicPath);
        data.html = data.html.replace(new RegExp('<!--I18nInfoToServer(.*?)I18nInfoToServer-->', 'g'), (match, arg) => match.replace(arg, JSON.stringify(i18nAssets))); // Tell webpack to move on

        cb(null, data);
      });
    });
  }

  apply(compiler) {
    if (i18n.chunkSplitEnable) {
      this.withI18nSpitHandling(compiler);
    } else {
      this.withoutI18nSpitHandling(compiler);
    }
  }

  withoutI18nSpitHandling(compiler) {
    compiler.hooks.emit.tap('I18NInjectIntoIndexPlugin', compilation => {
      // let cdns = Object.keys(this.publicPaths);
      if (i18nObj === null) {
        const i18nFiles = Object.keys(compilation.assets).filter(assert => assert.indexOf(`i18n${_path.default.sep}`) !== -1); //hook for i18n url contains i18n/ may cause problem

        i18nObj = i18nFiles.reduce((res, next) => {
          const fileName = next.replace(`i18n${_path.default.sep}`, '');
          const splittedFileName = fileName.split('.');
          /* if (this.isDevelopment) {
            res[splittedFileName[0]] = `${this.publicPath}/i18n/${fileName}`;
          } else {
            res[splittedFileName[0]] = fileName;
          } */

          res[splittedFileName[0]] = `${this.publicPath}/i18n/${fileName}`;
          return res;
        }, {});
      }

      const [indexFile] = Object.keys(compilation.assets).filter(filename => /\.html$/g.test(filename));

      if (indexFile) {
        const source = compilation.assets[indexFile].source();
        compilation.assets[indexFile] = new _webpackSources.RawSource(source.replace(new RegExp('<!--I18nInfoToServer(.*)I18nInfoToServer-->', 'g'), (match, arg) => match.replace(arg, JSON.stringify(i18nObj))));
      }
    });
  }

}

exports.default = I18NInjectIntoIndexPlugin;