/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

"use strict";

/* global dump: false, Cu: false, Ci: false, Cr: false, Components: false */

var EXPORTED_SYMBOLS = ["JSUnitCommandLine"];

const Cm = Components.manager;
Cm.QueryInterface(Ci.nsIComponentRegistrar);

const JSUnit = ChromeUtils.import("chrome://jsunit/content/modules/jsunit-main.jsm").JSUnit;
const Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
const {
  setTimeout,
  clearTimeout
} = ChromeUtils.import("resource://gre/modules/Timer.jsm");


function DEBUG_LOG(str) {
  dump("jsunit-service.js: " + str + "\n");
}

var gStartTime;


function startCmdLineTests(fileName, logFileName) {
  var appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].getService(Ci.nsIAppStartup);
  gStartTime = Date.now();

  JSUnit.init(false, logFileName);
  JSUnit.printMsg("Starting JS unit tests " + fileName + "\n");

  try {
    try {
      // ensure cache is deleted upon next application start
      Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).invalidateCachesOnRestart();
      JSUnit.executeScript(fileName, false, true);
    } catch (ex) {
      JSUnit.logTestResult("Exception occurred:\n" + ex.toString(), null, "");
      dump("** Tests aborted **\n");
    }
    JSUnit.printStats();
  } catch (x) {}

  appStartup.quit(Ci.nsIAppStartup.eForceQuit);
}

var JSUnitCommandLine = {
  startup: function() {
    dump("JSUnit: startup\n");
    setTimeout(function _f() {
      dump("JSUnit starting tests\n");
      startCmdLineTests("main.js", null);
    }, 3000);
  }
};