"use strict";

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

var _lodash = _interopRequireDefault(require("lodash"));

var _chalk = _interopRequireDefault(require("chalk"));

var _formatWebpackMessages = _interopRequireDefault(require("react-dev-utils/formatWebpackMessages"));

var _newregexp = _interopRequireDefault(require("newregexp"));

var _core = require("@reactant/core");

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

const _process = process,
      env = _process.env;

function handleStats(stats, config) {
  const ignore = config.ignore,
        options = config.options;
  let messages = {};

  if (options.debug) {
    messages = stats.toJson({}, true);
  } else {
    messages = (0, _formatWebpackMessages.default)(stats.toJson('verbose'));
  }

  const warnings = filterMessages(messages.warnings, ignore.warnings, config);

  if (warnings.length) {
    if (env.CI && env.CI.toLowerCase() !== 'false') {
      _core.log.info(_chalk.default.yellow('\ntreating warnings as errors because `CI = true`\n' + 'most CI servers set it automatically'));

      _core.log.error(`\n${warnings.join('\n\n')}\n`);
    } else {
      _core.log.warn(`\n${warnings.join('\n\n')}\n`);
    }
  }

  const errors = filterMessages(messages.errors, ignore.errors, config);
  if (errors.length) _core.log.error(`\n${errors.join('\n\n')}\n`);
  return {
    errors,
    messages,
    warnings
  };
}

function filterMessages(messages, ignore = [], config) {
  const options = config.options;
  if (options.debug) return messages;
  return _lodash.default.filter(messages, message => {
    let filter = false;
    ignore.forEach(ignoreItem => {
      if (/^\/.*\/[a-z]*$/.test(ignoreItem)) {
        const regex = (0, _newregexp.default)(ignoreItem);
        if (regex.test(message)) filter = true;
      } else if (message.indexOf(ignoreItem) > -1) {
        filter = true;
      }

      return !filter;
    });
    return !filter;
  });
}