"use strict";

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

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

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

var _redis = _interopRequireDefault(require("redis"));

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

var _log = require("../utils/log");

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

let options = (0, _utils.getOptions)();
let {
  app: {
    branch,
    redisHost,
    redisPort
  }
} = options;

class reportGeneratePlugin {
  apply(compiler) {
    compiler.hooks.emit.tapAsync('reportGeneratePlugin', (compilation, callback) => {
      function formatBytes(bytes) {
        if (bytes) {
          let isNegative;

          if (bytes < 0) {
            bytes = bytes * -1; //eslint-disable-line

            isNegative = true;
          }

          if (bytes < 1024) {
            if (isNegative) {
              return `- ${bytes} Bytes`;
            }

            return `${bytes} Bytes`;
          } else if (bytes < 1048576) {
            if (isNegative) {
              return `- ${(bytes / 1024).toFixed(3)} KB`;
            }

            return `${(bytes / 1024).toFixed(3)} KB`;
          } else if (bytes < 1073741824) {
            if (isNegative) {
              return `- ${(bytes / 1048576).toFixed(3)} MB`;
            }

            return `${(bytes / 1048576).toFixed(3)} MB`;
          }

          if (isNegative) {
            return `- ${(bytes / 1073741824).toFixed(3)} GB`;
          }

          return `${(bytes / 1073741824).toFixed(3)} GB`;
        }
      }

      let client = _redis.default.createClient(redisPort, redisHost);

      client.on('connect', () => {
        (0, _log.log)('Redis client connected');
      });
      client.on('error', err => {
        (0, _log.log)(`Something went wrong ${err}`);
      });

      if (_fs.default.existsSync(_path.default.resolve(process.cwd(), 'build', 'stats.json'))) {
        let statsJSON = _fs.default.readFileSync(_path.default.resolve(process.cwd(), 'build', 'stats.json'), 'utf8');

        statsJSON = JSON.parse(statsJSON);
        let finalObj = {};
        let branchName = branch ? branch : (0, _utils.getCurrentBranch)();
        (0, _log.log)(branchName);
        statsJSON.assets.forEach(assetObj => {
          let nameSplitList = assetObj.name.split('/')[assetObj.name.split('/').length - 1].split('.'); // eslint-disable-line

          let [, hash] = nameSplitList;
          let name = `${nameSplitList[0]}.${nameSplitList[2]}`;
          let {
            size
          } = assetObj;
          let tempObject = {
            name,
            hash,
            size
          }; // eslint-disable-next-line

          if (!finalObj.hasOwnProperty(name)) {
            finalObj[name] = tempObject;
          }
        });
        client.exists(branchName, (err, bool) => {
          if (!bool) {
            client.set(branchName, JSON.stringify(finalObj), _redis.default.print);
            client.quit();
          } else {
            let reportObj = {
              increased: [],
              hashChanged: [],
              branchName
            };
            client.get(branchName, (err, reply) => {
              if (err) {
                (0, _log.log)(err);
              } else {
                reply = JSON.parse(reply); // eslint-disable-line

                Object.keys(reply).forEach(fileName => {
                  // eslint-disable-next-line
                  if (finalObj.hasOwnProperty(fileName)) {
                    if (parseInt(reply[fileName].size) < parseInt(finalObj[fileName].size)) {
                      reportObj.increased.push({
                        name: fileName,
                        size: {
                          old: formatBytes(reply[fileName].size),
                          new: formatBytes(finalObj[fileName].size),
                          diff: formatBytes(parseInt(finalObj[fileName].size) - parseInt(reply[fileName].size))
                        }
                      });
                    }

                    if (reply[fileName].hash !== finalObj[fileName].hash) {
                      reportObj.hashChanged.push({
                        name: fileName,
                        hash: {
                          old: reply[fileName].hash,
                          new: finalObj[fileName].hash
                        }
                      });
                    }
                  }
                });
                let json = JSON.stringify(reportObj);

                _fs.default.writeFile(_path.default.resolve(process.cwd(), 'build', 'buildtrack.js'), `let statsJson=${json}`, err => {
                  if (err) {
                    throw err;
                  }

                  (0, _log.log)('Stats Json generated!');
                });
              }
            });
            client.set(branchName, JSON.stringify(finalObj), _redis.default.print); // fs.copyFileSync(
            //   path.resolve(
            //     process.cwd(),
            //     'node_modules',
            //     '@zohodesk',
            //     'react-cli',
            //     'lib',
            //     'utils',
            //     'buildstats.html'
            //   ),
            //   path.resolve(process.cwd(), 'build', 'buildstats.html')
            // );

            client.quit();
            callback && callback();
          }

          if (err) {
            (0, _log.log)(err);
          }
        });
      }
    });
  }

}

exports.default = reportGeneratePlugin;