"use strict";

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

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

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

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

//import { getI18nFileUrlPathTemplate } from './I18nSplitPlugin/utils/getI18nFileUrlPathTemplate';
//import { getOptions } from '../utils';
//import I18nKeysIdentifer from './I18nSplitPlugin/I18nKeysIdentifer';
//import { replaceCssDirTemplateMapper } from './RtlSplitPlugin/replaceCssDirTemplate';
// const {
//   css: { enableRTLSplit },
//   i18n: { chunkSplitEnable }
// } = 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.isChunkHasI18n(chunk))
          //     .map(chunk =>
          //       getI18nFileUrlPathTemplate(
          //         compilation,
          //         chunk,
          //         this.i18nFileNameTemplate,
          //         '@locale@'
          //       )
          //     )
          //   : [];

          let initalI18nAssets = []; //chunkSplitEnable &&

          compilation.chunks.filter(c => !this.isInitialChunk(c)) //.filter(chunk => I18nKeysIdentifer.isChunkHasI18n(chunk))
          .forEach(chunk => {
            // let isInitial = this.isInitialChunk(chunk);
            allChunkUrls = allChunkUrls.concat(chunk.files); // allI18nAssets.push(
            //   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 = replaceCssDirTemplateMapper(
          //     initialChunkUrls,
          //     cssDirTemplate
          //   );
          //   allChunkUrls = 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);
        }
      });
    });
  }

} // compiler.hooks.thisCompilation.tap('AddAssetPlugin', compilation => {
//   compilation.hooks.processAssets.tapPromise(tapOptions, async () => {
//     let source;
//     if (typeof this.source === 'string') {
//       if (compilation.getAsset(this.filePath)) {
//         // Skip emitting the asset again because it's immutable
//         return;
//       }
//       source = this.source;
//     } else {
//       source = await this.source(compilation);
//     }
//     compilation.emitAsset(this.filePath, new RawSource(source));
//   });
// });
//  getContentHash(compiler, compilation, source) {
//   const { outputOptions } = compilation;
//   const { hashDigest, hashDigestLength, hashFunction, hashSalt } =
//     outputOptions;
//   const hash = compiler.webpack.util.createHash(
//     /** @type {string} */ (hashFunction)
//   );
//   if (hashSalt) {
//     hash.update(hashSalt);
//   }
//   hash.update(source);
//   const fullContentHash = hash.digest(hashDigest);
//   return fullContentHash.toString().slice(0, hashDigestLength);
// }
// const contentHash = CopyPlugin.getContentHash(
//   compiler,
//   compilation,
//   source.buffer()
// );
//hash same as index.html file ??


exports.default = ServiceWorkerPlugin;