"use strict";

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

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

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

var _jsonHelper = require("../utils/jsonHelper");

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

let 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 = [];
  let testCaseFiles = [];
  let jsonData;

  if (_fs.default.existsSync('./coverageTest/result.json')) {
    jsonData = JSON.parse(_fs.default.readFileSync('./coverageTest/result.json', 'utf8'));
  }

  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 relatPath = filePath.replace(process.cwd(), '').substring(1);
    let fileJson = {};
    fileJson.testPath = testResult.testFilePath;
    fileJson.sourcePath = filePath;
    fileJson.data = testResult;
    testFilesArr.push(fileJson);

    if (jsonData.FILES.includes(relatPath) || jsonData.FILES.includes(testResult.testFilePath.replace(process.cwd(), ''))) {
      jsonData.FILES.includes(relatPath) ? testCaseFiles.push(relatPath) : jsonData.FILES.includes(testResult.testFilePath.replace(process.cwd(), '')) ? testCaseFiles.push(testResult.testFilePath.replace(process.cwd(), '')) : '';
    }
  });
  let coverageSummary = {};

  if (_fs.default.existsSync('./commitCoverage/coverage-summary.json')) {
    coverageSummary = _fs.default.readFileSync('./commitCoverage/coverage-summary.json').toString();

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

  let excludeTestArray = '{}';

  if (_fs.default.existsSync('./__testUtils__/conf/excludeTest.json')) {
    excludeTestArray = _fs.default.readFileSync('./__testUtils__/conf/excludeTest.json').toString();

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

  let coverageJson = JSON.parse(coverageSummary);
  let linesPercent = 0;
  let functionPercent = 0;
  let statementPerment = 0;
  let branchesPercent = 0;
  let fileList = '<h4>Changed files in last code check-in</h4><ul>';
  let i = 0;
  let excludeTestJSON = JSON.parse(excludeTestArray);

  if (Object.keys(excludeTestArray).length > 0) {
    jsonData.FILES = jsonData.FILES.filter(function (value) {
      if (!excludeTestJSON.test.exclude.includes(value)) {
        let excludeDir = excludeTestJSON.test.exclude.filter(function (excludeFile) {
          if (value.indexOf(excludeFile) > -1) {
            return value;
          }
        });

        if (excludeDir.length > 0) {
          return null;
        }

        return value;
      }

      return null;
    });
  }

  for (i; i < jsonData.FILES.length; i++) {
    let coverageData;
    let curSourceFile = jsonData.FILES[i];
    curSourceFile.replace(process.cwd(), '').substring(1);
    fileList = `${fileList}<li>${curSourceFile}</li>`;
    Object.keys(coverageJson).forEach(coverageFile => {
      if (coverageFile.includes(curSourceFile) || coverageFile === 'total') {
        coverageData = coverageJson[coverageFile];
      }
    });

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

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

  fileList = `${fileList}</ul>`;

  if (!jsonData.FILES.length) {
    fileList = '<div></div>';
  }

  let uncoveredList = '<h4>Uncovered files :- </h4><ul>';
  let fileCoverage = 0;

  if (jsonData.FILES.length > 0) {
    fileCoverage = testCaseFiles.length / jsonData.FILES.length * 100;
  }

  fileCoverage = fileCoverage.toFixed(2);
  fileCoverage = Number(fileCoverage);

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

  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);

  if (Number.isNaN(coverage)) {
    (0, _jsonHelper.jsonHelper)(`${process.cwd()}/result.json`, 'tests.modifiedFileUnitCase.testInfo', 'can\'t get coverage for this test');
    coverage = 0;
    uncoveredList = uncoveredList + 'No Component changes with this build, You can proceed this build </ul>';
  } else {
    (0, _jsonMaker.default)(inp, coverage, true, 'modifiedFileUnitCase', fileCoverage);
    (0, _jsonHelper.jsonHelper)(`${process.cwd()}/result.json`, 'tests.modifiedFileUnitCase.isBuildVerified', coverage > 60);
    (0, _jsonHelper.jsonHelper)(`${process.cwd()}/result.json`, 'tests.modifiedFileUnitCase.testInfo', 'Test coverage value generated'); // jsonHelper(
    //     `${process.cwd()}/result.json`,
    //     'testInfo.isBuildVerified',
    //     coverage > 60
    // );

    (0, _jsonHelper.setTestInfoStatus)(`${process.cwd()}/result.json`, true
    /*coverage > 60*/
    );

    if (coverage < 60) {
      (0, _jsonHelper.jsonHelper)(`${process.cwd()}/result.json`, 'testInfo.failures', [{
        type: 'modifiedUnitcases',
        message: 'Need to cover 60% above for changed files'
      }]);
      uncoveredList = uncoveredList + 'Ask developer to cover 60% above for changed files </ul>';
    } else {
      uncoveredList = uncoveredList + 'You can proceed this build </ul>';
    }

    (0, _utils.log)(`COVERAGE ${coverage}%`);
  }

  let html = `<html><head><style>.red{font-weight:bold;color:red;}.green{font-weight:bold;color:green;}</style></head><body><br/>CODE COVERAGE <span class="${coverage < 60 ? 'red' : 'green'}">${coverage}%</span> <br/> less than 60% consider failure<br/><br/> FILE COVERAGE:<span class="${fileCoverage < 60 ? 'red' : 'green'}">${fileCoverage}%</span> <br/> less than 60% consider failure${fileList}${uncoveredList}</body></html>`;

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

    _fs.default.writeFileSync('./coverageTest/index.html', html, 'utf8');
  } else {
    _fs.default.writeFileSync('./coverageTest/index.html', html, 'utf8');
  }

  return inp;
};

module.exports = result;