'use strict';

const path = require('path');

const tools = require('../tools');
const configUtils = require('../../csdr/config/config-utils');

module.exports.run = () => {
  return Promise.resolve()
    .then(() => {
      tools.logTitle('Bundle analyzer remote');

      const remoteName = tools.getArgs().root;

      if (!remoteName) {
        tools.logError('ERROR!! Remote not provided as argument');
        return;
      }

      const remote = configUtils.remotes.getRemote(remoteName);

      if (!tools.isDirExists(remote.paths.dist)) {
        tools.logError('ERROR!! Remote has not been built, unable to analyze -- build your remote using the remote:build REMOTE_NAME script');
        return
      }

      if (!tools.isFileExists(path.join(remote.paths.dist, 'stats.json'))) {
        tools.logError(`ERROR!! Unable to find stats.json file in ${remote.paths.dist} -- build your remote using the --statsJson parameter`);
        return;
      }

      return tools.runScript(`webpack-bundle-analyzer ${remote.paths.dist}/stats.json`);
    })

    .catch((e) => {
      throw e;
    })
}
