"use strict";

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

var _webpack = require("webpack");

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

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

var _addHashToFilePath = require("./addHashToFilePath");

var _cssClassNameGenerate = require("../../loaderConfigs/cssClassNameGenerate");

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

class TPHashMappingPlugin {
  constructor(options) {
    this.fileMappings = options.fileMappings;
    this.tpFolder = options.tpFolder;
  }

  apply(compiler) {
    new _webpack.DefinePlugin(this.getFiles()).apply(compiler);
  }

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

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

        const generatedHash = (0, _cssClassNameGenerate.getHash)(fileContent, fileInfo.hashLength || 10);
        const outputFilePath = (0, _addHashToFilePath.addHashToFilePath)(filePath, generatedHash);

        _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;
  }

}

exports.TPHashMappingPlugin = TPHashMappingPlugin;