#!/usr/bin/env node

var util  = require("util"),
    fs    = require("fs"),
    PEG   = require("../lib/peg"),
    QUnit = require("./vendor/qunit/qunit");

var failedAssertions = [];

function bold(s)    { return "\u001B[1m"  + s + "\u001B[22m"; };
function message(s) { return "\u001B[35m" + s + "\u001B[39m"; };
function ok(s)      { return "\u001B[32m" + s + "\u001B[39m"; };
function error(s)   { return "\u001B[31m" + s + "\u001B[39m"; };

function indent(s) { return s.replace(/^/gm, "    "); }

QUnit.init();
QUnit.config.blocking   = true;
QUnit.config.updateRate = 0;

QUnit.moduleStart(function(details) {
  util.puts("");
  util.puts(bold(details.name));
});

QUnit.testStart(function(details) {
  failedAssertions = [];
});

QUnit.testDone(function(details) {
  if (details.failed == 0) {
    util.puts('✔ ' + details.name);
  } else {
    util.puts(error('✖ ' + details.name));
    util.puts("");
    failedAssertions.forEach(function(assertion) {
      util.puts(assertion);
    });
  }
});

QUnit.log(function(details) {
  var output = "";

  if (details.result) { return; }

  if (details.message) {
    output += indent("Message:  " + message(details.message)) + "\n";
  }
  if (details.actual && details.expected) {
    output += indent("Expected: " + QUnit.jsDump.parse(details.expected)) + "\n";
    if (details.actual != details.expected) {
      output += indent("Actual:   " + QUnit.jsDump.parse(details.actual));
    }
  }

  failedAssertions.push(output);
});

QUnit.done(function(details) {
  util.puts("");
  if (details.failed > 0) {
    util.puts(bold(error("FAILURES: "))
      + details.failed + "/"
      + details.total + " assertions failed ("
      + details.runtime + " ms)"
    );
  } else {
    util.puts(bold(ok('OK: '))
      + details.total + " assertions ("
      + details.runtime + " ms)"
    )
  }
});

[
  "helpers.js",
  "compiler-test.js",
  "compiler/passes/report-missing-rules-test.js",
  "compiler/passes/report-left-recursion-test.js",
  "compiler/passes/remove-proxy-rules-test.js",
  "compiler/passes/compute-var-names-test.js",
  "compiler/passes/compute-params-test.js"
].forEach(function(file) {
  eval("with (QUnit) {" + fs.readFileSync(__dirname + "/" + file, "utf8") + "}");
});

QUnit.start();