"use strict";

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

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

var _jsonMaker = _interopRequireDefault(require("./jsonMaker"));

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

let unitTestReport = [];

const result = inp => {
  inp.endTime = Date.now();
  let testPathPattern = process.argv[process.argv.length - 1];

  if (testPathPattern.indexOf('--') !== -1) {
    testPathPattern = '';
  } else {
    testPathPattern = _fs.default.realpathSync(process.cwd());
  }

  let testPathRegex = new RegExp(testPathPattern);
  let {
    testResults
  } = inp;
  let testFilesArr = [];
  testResults.forEach(testResult => {
    let filePath = testResult.testFilePath;

    if (!testPathRegex.test(filePath)) {
      return;
    }

    filePath = filePath.replace('.spec', '');
    filePath = filePath.replace('/__tests__', '');
    filePath = filePath.replace('/__test__', '');
    let fileJson = {};
    fileJson.testPath = testResult.testFilePath;
    fileJson.sourcePath = filePath;
    fileJson.data = testResult;
    testFilesArr.push(fileJson);
    testResult.testResults && testResult.testResults.filter(t => t.status === 'failed').forEach(t => {
      unitTestReport.push({
        title: t.title,
        fullName: t.fullName,
        filePath: testResult.testFilePath
      });
    });
  });

  let coverageSummary = _fs.default.readFileSync('./coverage/coverage-summary.json').toString();

  if (coverageSummary.indexOf('\\') !== -1) {
    coverageSummary = coverageSummary.replace(/\\/g, '\\\\');
  }

  let coverageJson = JSON.parse(coverageSummary);
  let linesPercent = 0;
  let functionPercent = 0;
  let statementPerment = 0;
  let branchesPercent = 0;
  let i = 0;

  for (i; i < testFilesArr.length; i++) {
    let curSourceFile = testFilesArr[i].sourcePath;
    let coverageData = coverageJson[curSourceFile];

    if (!coverageData) {
      (0, _utils.log)(`Can't able to find source for ${testFilesArr[i].testPath}\n Or The spec file getting failed during test. Please check the file name and the path is correct for test file or Make them pass.`);
      continue;
    }

    linesPercent += coverageData.lines.pct;
    functionPercent += coverageData.functions.pct;
    statementPerment += coverageData.statements.pct;
    branchesPercent += coverageData.branches.pct;
  }

  let totalLinesPercent = linesPercent / (i * 100) * 100;
  let totalFunctionPercent = functionPercent / (i * 100) * 100;
  let totalStatementPercent = statementPerment / (i * 100) * 100;
  let totalBranchesPercent = branchesPercent / (i * 100) * 100;
  let totalPercentage = totalLinesPercent + totalFunctionPercent + totalStatementPercent + totalBranchesPercent;
  let coverage = (totalPercentage / 4).toFixed(2);
  coverage = Number(coverage);
  (0, _jsonMaker.default)(inp, coverage, 'Yes', 'unitcase');

  if (Number.isNaN(coverage)) {
    (0, _utils.log)('This build does\'t have any JS changes!');
    coverage = 0;
  } else {
    (0, _utils.log)(`COVERAGE ${coverage}%`);
  }

  let html = `<html>
	<head>
	<style>
	.red{
		font-weight:bold;
		color:red;
	}
	.green{
		font-weight:bold;
		color:green;
	}
	table
		{
    font-family: arial, sans-serif;
    border-collapse: collapse;
		}

		td, th
		{
    border: 1px solid #dddddd;
    padding: 8px;
		}
	</style>
	</head>
		<body>
			<table>
			<tr>
				<th>Title</th>
				<th>FullName</th>
				<th>Test Case Path</th>
			</tr>
			${unitTestReport.map(t => `<tr>
					<td>${t.title}</td>
					<td>${t.fullName}</td>
					<td>${t.filePath}</td>
				</tr>`)}
			</table>
			<br/>COVERAGE <span class="${coverage < 60 ? 'red' : 'green'}">${coverage}%</span> <br/> less than 60% consider failure
		</body>
	</html>
		`;

  if (!_fs.default.existsSync('./unittest')) {
    _fs.default.mkdirSync('./unittest');
  }

  _fs.default.writeFileSync('./unittest/index.html', html, 'utf8');

  return inp;
};

module.exports = result;