"use strict";

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

var _webpack = require("webpack");

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

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

var _crypto = _interopRequireDefault(require("crypto"));

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

/**
 * Plugin that generates hash for the provided list of third party files
 * Map the provided key with the file hash and add it to the list of exisiting global constants.
 * Plugin in turn uses the defineplugin to generate global constants. 
 */
class TPHashMappingPlugin {
  constructor(options) {
    this.fileMappings = options.fileMappings;
    this.tpFolder = options.tpFolder;
    return new _webpack.DefinePlugin(this.getFiles());
  }

  getHash(content) {
    let hash = _crypto.default.createHash('md5');

    let data = hash.update(content, 'utf-8');
    let gen_hash = data.digest('hex');
    return gen_hash;
  }

  getFiles() {
    let hashMapping = {};
    this.fileMappings.forEach(fileInfo => {
      let filePath = `${_path.default.join(this.tpFolder, fileInfo.filePath, fileInfo.fileName)}`;

      if (_fs.default.existsSync(filePath)) {
        let fileContent = _fs.default.readFileSync(filePath, {
          encoding: 'utf-8'
        });

        let generatedHash = this.getHash(fileContent);
        let outputFileSplit = fileInfo.fileName.split('.');
        outputFileSplit.splice(outputFileSplit.length - 1, 0, generatedHash);
        let outputFileName = outputFileSplit.join('.');
        let outputFilePath = `${_path.default.join(this.tpFolder, fileInfo.filePath, outputFileName)}`;

        _fs.default.writeFileSync(outputFilePath, fileContent);

        hashMapping[fileInfo.key] = JSON.stringify(generatedHash);
      } else {
        throw new Error(`Third party file ${fileInfo.fileName} does not exist`);
      }
    });
    return hashMapping;
  }

}

var _default = TPHashMappingPlugin;
exports.default = _default;