"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.paintCiResults = exports.paintBuildResults = exports.paintSummarySpecsResults = exports.paintAllSpecsResults = exports.paintSpecsResults = exports.paintLog = exports.paintHeader = exports.paintBitProp = exports.formatBitString = exports.formatPlainComponentItemWithVersions = exports.formatPlainComponentItem = exports.formatBit = exports.formatNewBit = void 0;

function _chalk() {
  const data = _interopRequireDefault(require("chalk"));

  _chalk = function () {
    return data;
  };

  return data;
}

function _ttyTable() {
  const data = _interopRequireDefault(require("tty-table"));

  _ttyTable = function () {
    return data;
  };

  return data;
}

function _specsResults() {
  const data = _interopRequireDefault(require("../consumer/specs-results/specs-results"));

  _specsResults = function () {
    return data;
  };

  return data;
}

function _mergeVersion() {
  const data = require("../consumer/versions-ops/merge-version/merge-version");

  _mergeVersion = function () {
    return data;
  };

  return data;
}

const formatNewBit = ({
  name
}) => _chalk().default.white('     > ') + _chalk().default.cyan(name);

exports.formatNewBit = formatNewBit;

const formatBit = ({
  scope,
  name,
  version
}) => _chalk().default.white('     > ') + _chalk().default.cyan(`${scope ? `${scope}/` : ''}${name} - ${version ? version.toString() : 'latest'}`);

exports.formatBit = formatBit;

const formatPlainComponentItem = ({
  scope,
  name,
  version,
  deprecated
}) => _chalk().default.cyan(`- ${scope ? `${scope}/` : ''}${name}@${version ? version.toString() : 'latest'}  ${deprecated ? _chalk().default.yellow('[deprecated]') : ''}`);

exports.formatPlainComponentItem = formatPlainComponentItem;

const formatPlainComponentItemWithVersions = (component, importDetails) => {
  const status = importDetails.status;
  const id = component.id.toStringWithoutVersion();
  const versions = importDetails.versions.length ? `new versions: ${importDetails.versions.join(', ')}` : ''; // $FlowFixMe component.version should be set here

  const usedVersion = status === 'added' ? `, currently used version ${component.version}` : '';

  const getConflictMessage = () => {
    if (!importDetails.filesStatus) return '';
    const conflictedFiles = Object.keys(importDetails.filesStatus) // $FlowFixMe file is set
    .filter(file => importDetails.filesStatus[file] === _mergeVersion().FileStatus.manual);
    if (!conflictedFiles.length) return '';
    return `(the following files were saved with conflicts ${conflictedFiles.map(file => _chalk().default.bold(file)).join(', ')}) `;
  };

  const deprecated = component.deprecated ? _chalk().default.yellow('deprecated') : '';
  return `- ${_chalk().default.green(status)} ${_chalk().default.cyan(id)} ${versions}${usedVersion} ${getConflictMessage()}${deprecated}`;
};

exports.formatPlainComponentItemWithVersions = formatPlainComponentItemWithVersions;

const formatBitString = bit => _chalk().default.white('     > ') + _chalk().default.cyan(`${bit}`);

exports.formatBitString = formatBitString;

const paintBitProp = (key, value) => {
  if (!value) return '';
  return `${_chalk().default.magenta(key)} -> ${value}\n`;
};

exports.paintBitProp = paintBitProp;

const paintHeader = value => {
  if (!value) return '';
  return `${_chalk().default.underline(value)}\n`;
};

exports.paintHeader = paintHeader;

const paintAuthor = (email, username) => {
  if (email && username) {
    return _chalk().default.white(`author: ${username} <${email}>\n`);
  } else if (email && !username) {
    return _chalk().default.white(`author: <${email}>\n`);
  } else if (!email && username) {
    return _chalk().default.white(`author: ${username}\n`);
  }

  return '';
};

const paintLog = ({
  message,
  date,
  tag,
  username,
  email
}) => {
  return _chalk().default.yellow(`tag ${tag}\n`) + paintAuthor(email, username) + _chalk().default.white(`date: ${date}\n`) + (message ? _chalk().default.white(`\n      ${message}\n`) : '');
};

exports.paintLog = paintLog;

const successTest = test => {
  return `✔   ${_chalk().default.white(test.title)} - ${_chalk().default.cyan(`${test.duration}ms`)}`;
};

const failureTest = test => {
  return `❌   ${_chalk().default.white(test.title)} - ${_chalk().default.cyan(`${test.duration}ms`)}
    ${_chalk().default.red(test.err.message)}`;
};

const paintMissingTester = componentId => {
  const componentIdBold = _chalk().default.bold(componentId);

  return _chalk().default.bold.red(`tester for component: ${componentIdBold} is not defined`);
};

const paintTest = test => {
  return test.pass ? successTest(test) : failureTest(test);
}; // Failures which are not on tests, for example on before blocks


const paintGeneralFailure = (failure, verbose) => {
  const duration = failure.duration ? ` - ${_chalk().default.cyan(`${failure.duration}ms`)}` : '';
  let errStack = '';

  if (verbose && failure.err) {
    errStack = failure.err.stack;
  }

  return `❌   ${_chalk().default.white(failure.title)} ${duration}
    ${_chalk().default.red(failure.err.message)}
    ${_chalk().default.red(errStack)}`;
};

const paintStats = results => {
  const statsHeader = results.pass ? _chalk().default.underline.green('\ntests passed') : _chalk().default.underline.red('\ntests failed');
  const fileName = results.specFile ? _chalk().default.white(`\nfile: ${results.specFile}`) : '';
  const totalDuration = results.stats && results.stats.duration !== undefined ? `total duration - ${_chalk().default.cyan(`${results.stats.duration}ms\n`)}` : '';
  return `${statsHeader}${fileName}\n${totalDuration}\n`;
};

const paintSpecsResults = (results, verbose = false) => {
  if (!results) return [];
  return results.map(specResult => {
    const stats = paintStats(specResult);
    const tests = specResult.tests ? `${specResult.tests.map(paintTest).join('\n')}\n` : '';
    const failures = specResult.failures ? `${specResult.failures.map(failure => paintGeneralFailure(failure, verbose)).join('\n')}\n` : '';
    const final = tests || failures ? stats + tests + failures : '';
    return final;
  });
};

exports.paintSpecsResults = paintSpecsResults;

const paintAllSpecsResults = (results, verbose = false) => {
  const childOutput = results.childOutput ? `${results.childOutput}\n` : '';
  if (results.results && results.results.length === 0) return `${childOutput}${_chalk().default.yellow('nothing to test')}`;
  const resultsOutput = results.results.map(result => {
    const idStr = result.componentId.toString();
    if (result.missingTester) return paintMissingTester(idStr);

    const componentId = _chalk().default.bold(idStr);

    if (result.specs) return componentId + paintSpecsResults(result.specs, verbose);
    return _chalk().default.yellow(`tests are not defined for component: ${componentId}`);
  }).join('\n');
  return `${childOutput}\n${resultsOutput}`;
};

exports.paintAllSpecsResults = paintAllSpecsResults;

const paintSummarySpecsResults = results => {
  if (results.length <= 1) return ''; // it there are no results or only one result, no need for summary

  const summaryHeader = [];
  summaryHeader.push({
    value: 'Component ID',
    width: 80,
    headerColor: 'cyan'
  });
  summaryHeader.push({
    value: 'Specs Results',
    width: 50,
    headerColor: 'cyan'
  });

  const specsSummary = specResults => {
    const specsPassed = specResults.map(specResult => specResult.pass);
    const areAllPassed = specsPassed.every(isPassed => isPassed);
    return areAllPassed ? _chalk().default.green('passed') : _chalk().default.red('failed');
  };

  const summaryRows = results.map(result => {
    const componentId = _chalk().default.bold(result.componentId.toString());

    if (result.missingTester) return [componentId, _chalk().default.bold.red('tester is not defined')];
    if (result.specs) return [componentId, specsSummary(result.specs)];
    return [componentId, _chalk().default.yellow('tests are not defined')];
  });
  const summaryTable = new (_ttyTable().default)(summaryHeader, summaryRows);
  return summaryTable.render();
};

exports.paintSummarySpecsResults = paintSummarySpecsResults;

const paintBuildResults = buildResults => {
  if (buildResults) {
    const statsHeader = _chalk().default.underline.green('\nbuilt Files:\n');

    return statsHeader + buildResults.map(file => `${_chalk().default.cyan(`${file.path}`)}`).join('\n');
  }

  return '';
};

exports.paintBuildResults = paintBuildResults;

const paintCiResults = ({
  dists,
  specsResults
}) => {
  return paintBuildResults(dists) + paintSpecsResults(specsResults);
};

exports.paintCiResults = paintCiResults;