"use strict";

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

var _fs = _interopRequireDefault(require("fs"));

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

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

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

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

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

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

const {
  css: {
    enableRTLSplit
  },
  i18n: {
    chunkSplitEnable
  }
} = (0, _utils.getOptions)();

class ServiceWorkerPlugin {
  constructor(options) {
    this.i18nFileNameTemplate = options.i18nFileNameTemplate;
    this.fileName = options.fileName;
    this.serviceWorkerPath = options.filePath;
    this.writePath = options.exitPath;
    this.replaceText = options.replaceText; // this.publicPaths = options.publicPaths;
  }

  isInitialChunk(chunk) {
    if ('canBeInitial' in chunk) {
      return chunk.canBeInitial();
    }

    return chunk.isInitial();
  }

  apply(compiler) {
    compiler.hooks.emit.tap('ServiceWorkerPlugin', compilation => {
      _fs.default.readFile(this.serviceWorkerPath, 'utf-8', (err, data) => {
        if (err) {
          throw new Error(err);
        } else {
          /* const extractedChunks = compilation.chunks.filter(chunk => {
            if ('canBeInitial' in chunk) {
              return chunk.canBeInitial();
            }
            return chunk.isInitial();
          }); */
          // let [js, css, , , i18nPublicPath] = this.publicPaths;
          // let initialChunkUrls = [];
          let allChunkUrls = [];
          let allI18nAssets = [];
          let entrypoint = compilation.entrypoints.get('main');
          let initialChunkUrls = entrypoint.getFiles();
          const cssDirTemplate = '@dir@';
          /**
           * NOTE:
           *  if chunkSplitEnable is false means,
           *    serviceWorker will get i18n files path for html
           */

          let initalI18nAssets = chunkSplitEnable ? entrypoint.chunks.filter(chunk => _I18nKeysIdentifer.default.isChunkHasI18n(chunk)).map(chunk => (0, _getI18nFileUrlPathTemplate.getI18nFileUrlPathTemplate)(compilation, chunk, this.i18nFileNameTemplate, '@locale@')) : [];
          chunkSplitEnable && compilation.chunks.filter(c => !this.isInitialChunk(c)).filter(chunk => _I18nKeysIdentifer.default.isChunkHasI18n(chunk)).forEach(chunk => {
            // let isInitial = this.isInitialChunk(chunk);
            allChunkUrls = allChunkUrls.concat(chunk.files);
            allI18nAssets.push((0, _getI18nFileUrlPathTemplate.getI18nFileUrlPathTemplate)(compilation, chunk, this.i18nFileNameTemplate, '@locale@'));
          });
          /** Removing source map files from getting added */

          initialChunkUrls = initialChunkUrls.filter(fileName => !fileName.endsWith('.map'));
          allChunkUrls = allChunkUrls.filter(fileName => !fileName.endsWith('.map'));

          if (enableRTLSplit) {
            initialChunkUrls = (0, _replaceCssDirTemplate.replaceCssDirTemplateMapper)(initialChunkUrls, cssDirTemplate);
            allChunkUrls = (0, _replaceCssDirTemplate.replaceCssDirTemplateMapper)(allChunkUrls, cssDirTemplate);
          }

          let mod = data.replace(this.replaceText, `
self.assets = ${JSON.stringify(initialChunkUrls.concat(initalI18nAssets))};
self.allChunks = ${JSON.stringify(allChunkUrls.concat(allI18nAssets))};`);

          if (!_fs.default.existsSync(this.writePath)) {
            _fs.default.mkdirSync(this.writePath, {
              recursive: true
            });
          }

          _fs.default.writeFileSync(_path.default.join(this.writePath, this.fileName), mod);
        }
      });
    });
  }

}

exports.default = ServiceWorkerPlugin;