/* eslint-env node */
'use strict';

const fs = require('fs');
const path = require('path');

const XUnitReporter = require('testem/lib/reporters/xunit_reporter');
const DisplayUtils = require('testem/lib/displayutils');

const TEST_RESULTS_PATH = 'test-results/data.xml';
const XUNIT_CONFIG = {get:function() {return 'false';}};

const DEFAULT_FEATURES = {
  saveToFile: false,
  showIfLogs: true,
  silent: false,
  showAllResults: false
};

function createTestResultsDir() {
  let directory = path.dirname(TEST_RESULTS_PATH);
  if (!fs.existsSync(directory)) {
    fs.mkdirSync(directory);
  }
}

function TestemReporter() {
  this.features = Object.assign({}, DEFAULT_FEATURES);

  if (process.env.CI) {
    this.features.saveToFile = true;
  }

  if (process.env.OUTPUT_ALL === 'true') {
    this.features.showAllResults = true;
  }

  XUnitReporter.call(this, this.features.silent, process.stdout, XUNIT_CONFIG);
  this._reportCount = 0;
}

TestemReporter.prototype = Object.create(XUnitReporter.prototype);
TestemReporter.prototype.constructor = TestemReporter;

TestemReporter.prototype.finish = function () {
  // Not calling super because it will print results to std out
  if (this.silent) {
    return;
  }
  this.endTime = new Date();

  createTestResultsDir();

  fs.writeFileSync(TEST_RESULTS_PATH, this.summaryDisplay());
};

TestemReporter.prototype.display = function(prefix, result) {
  if (this.silent) {
    return;
  }

  this._reportCount++;

  if (this.features.showAllResults || !result.passed || (this.features.showIfLogs && result.logs.length)) {
    this.out.write('\n');

    this.out.write(DisplayUtils.resultString(this.id++, prefix, result));
  }

  if (this._reportCount > 25) {
    this.out.write('.');
    this._reportCount = 0;
  }
};

module.exports = TestemReporter;
