"use strict";

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

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

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

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

var _fs = require("fs");

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

var _I18nKeysIdentifer = _interopRequireDefault(require("./I18nSplitPlugin/I18nKeysIdentifer"));

var _replaceCssDirTemplate = require("./RtlSplitPlugin/replaceCssDirTemplate");

var _logger = require("../logger");

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

// import { getShortI18nAssets } from './I18nSplitPlugin/utils/hashUtils';
const cliOptions = (0, _utils.getOptions)();
const {
  i18n: {
    chunkSplitEnable
  },
  css: {
    enableRTLSplit
  },
  efc: efcOptios
} = cliOptions;
const {
  createSDkFile
} = efcOptios; // for smap relate changes
// CdnChangePlugin
// SourceMapHookPlugin

class EFCTemplatePlugin {
  constructor(options = {}) {
    this.templateFilePath = _path.default.join(process.cwd(), options.templateFilePath);
    this.i18nFileNameTemplate = options.i18nFileNameTemplate;
    this.publicPath = options.publicPath; // NOTE: this logic may be needed for i18n splited file name with contenthash cases
    // this.i18nManifestFileName = options.i18nManifestFileName;
    // IMPORTANT: here we mergeing optionds  from  pacakge.json  and options via constructor
    // So when debugging consider this as well
    // this.options = Object.assign({}, efcOptios, options);

    this.entryPointName = options.entryPointName || 'efc';
    this.outputFile = efcOptios.outputFile.replace('[version]', efcOptios.version);
  } // NOTE: this logic may be needed for i18n splited file name with contenthash cases
  // getI18nManifest(compilation) {
  //   const i18nManifestFile =
  //     compilation.assets[this.options.i18nManifestFileName];
  //   if (i18nManifestFile) {
  //     const manifest = JSON.parse(i18nManifestFile.source());
  //     return manifest;
  //   }
  //   return {};
  // }


  getI18nAssetsStr(entryPoint, compilation) {
    // NOTE: we have used lang variable inside
    if (!chunkSplitEnable) {
      let i18nAsstes = {};
      const i18nFiles = Object.keys(compilation.assets).filter(assert => assert.indexOf(`i18n${_path.default.sep}`) !== -1); //hook for i18n url contains i18n/ may cause problem

      i18nAsstes = i18nFiles.reduce((res, i18nFilePath) => {
        const fileName = i18nFilePath.replace(`i18n${_path.default.sep}`, '');
        const splittedFileName = fileName.split('.');
        res[splittedFileName[0]] = i18nFilePath;
        return res;
      }, {});
      return `[${JSON.stringify(i18nAsstes)}[lang]]`;
    }

    const initalI18nAssets = entryPoint.chunks.filter(chunk => _I18nKeysIdentifer.default.isChunkHasI18n(chunk)).map(chunk => (0, _getI18nFileUrlPathTemplate.getI18nFileUrlPathTemplate)(compilation, chunk, this.i18nFileNameTemplate, '@locale@'));
    return `${JSON.stringify(initalI18nAssets)}.map(urlpath => urlpath.replace(/@locale@/g, lang))`;
  }

  templateReplacer(entryPoint, compilation) {
    const cssDirTemplate = '@dir@'; // const i18nManifest = this.getI18nManifest(compilation);

    const initialFiles = entryPoint.getFiles();
    const filteredInitialFiles = initialFiles.filter(file => /\.(css|js)$/.test(file));
    const initialJsFiles = filteredInitialFiles.filter(file => /\.js$/.test(file));
    let initialCssFiles = filteredInitialFiles.filter(file => /\.css$/.test(file));

    if (enableRTLSplit) {
      initialCssFiles = initialCssFiles.map(filePath => (0, _replaceCssDirTemplate.replaceCssDirTemplate)(filePath, cssDirTemplate));
    } // const i18nAssets = getShortI18nAssets(
    //   entryPoint.chunks,
    //   i18nManifest,
    //   '' // i18nJsPath
    // );


    const initalI18nAssets = this.getI18nAssetsStr(entryPoint, compilation, '' // i18nJsPath
    );
    const templateStr = (0, _fs.readFileSync)(this.templateFilePath).toString();
    return templateStr.replace('((\'getInitalAssets\'))', `function getInitalAssets(assetsType, lang) {
          if (assetsType === "js") {
            return ${JSON.stringify(initialJsFiles)}
          }
          if (assetsType === "css") {
            return ${JSON.stringify(initialCssFiles)}
          }
          if (assetsType === "i18n") {
            return ${initalI18nAssets};
          }
          return  [];
        }`).replace('((\'@dir@\'))', '\'@dir@\'').replace('((\'publicPath\'))', this.publicPath).replace('((\'@locale@\'))', '\'@locale@\'');
  }

  apply(compiler) {
    if (!createSDkFile) {
      return;
    }

    compiler.hooks.emit.tap('EFCTemplatePlugin', compilation => {
      const {
        entryPointName,
        outputFile
      } = this;
      const entryPoint = compilation.entrypoints.get(entryPointName);

      if (!entryPoint) {
        return;
      }

      if (!(0, _fs.existsSync)(this.templateFilePath)) {
        console.error(`EFC Template file not exists ${this.templateFilePath}`);
        return;
      }

      const source = new _webpackSources.RawSource(this.templateReplacer(entryPoint, compilation));
      compilation.assets[outputFile] = source;
      (0, _logger.messageLogger)('The EFC embedded code was created successfully..!!!');
    });
  }

}

exports.default = EFCTemplatePlugin;