var Cu = Components.utils;
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cr = Components.results;

const ioService=Components.classes["@mozilla.org/network/io-service;1"]
    .getService(Components.interfaces.nsIIOService);
const scriptableStream=Components
    .classes["@mozilla.org/scriptableinputstream;1"]
    .getService(Components.interfaces.nsIScriptableInputStream);

function getContents(URI) {
    var uri = ioService.newURI(URI, null, null);
    var channel = ioService.newChannelFromURI(uri);
    var input = channel.open();

    scriptableStream.init(input);
    var str = scriptableStream.read(input.available());
    scriptableStream.close();
    input.close();

    return str;
}

var jumlib = {};
Components.utils.import("resource://mozmill/modules/jum.js", jumlib);

var topsrcDir;
var timers = [];

function setupModule(module) {
    var localFile = Components.classes["@mozilla.org/file/local;1"]
        .createInstance(Components.interfaces.nsILocalFile);
    localFile.initWithPath(module.__file__);
    topsrcDir = localFile.parent.parent.path;

    module.controller = mozmill.getBrowserController();
}

function testFunc() {
    var mainWindow = controller.window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
        .getInterface(Components.interfaces.nsIWebNavigation)
        .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
        .rootTreeItem
        .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
        .getInterface(Components.interfaces.nsIDOMWindow);

    function Backend() {
        this._init();
    }

    Backend.prototype = {
        _init: function () {
            this._tab = mainWindow.gBrowser.addTab("about:home");

            this._tabBrowser = mainWindow.gBrowser.getBrowserForTab(this._tab);
        },

        connect: function(eventName, callback) {
            if (eventName == "load") {
                this._tabBrowser.addEventListener("load", function (aEvent) {
                    var doc = aEvent.originalTarget;

                    if (this._tabBrowser.contentDocument !== doc)
                        return;

                    callback();
                }.bind(this), true);
            } else if (eventName == "unload") {
                this._tabBrowser.addEventListener("unload", callback, true);
            } else {
                throw new Error();
            }
        },

        getContent: function(relativePath) {
            if (relativePath.match(/^file:/))
                return getContents(relativePath);
            return getContents("file://" + topsrcDir + "/" + relativePath);
        },

        loadURI: function(uri) {
            this._tabBrowser.loadURI(uri);
        },

        assertEquals: function(a, b) {
            jumlib.assertEquals(a, b);
            if (a !== b)
                throw new Error(String(a) + '!==' + String(b));
        },

        injectScript: function(src) {
            this._tabBrowser.contentWindow.wrappedJSObject.eval(src);
        },

        getLocation: function() {
            return String(this._tabBrowser.contentWindow.location);
        },

        getTextFromNode: function(nodeName) {
            return this._tabBrowser.contentDocument.getElementById(nodeName).textContent;
        },

        print: function(str) {
            dump(str);
        },

        finish: function() {
            mainWindow.gBrowser.removeTab(this._tab);
        },

        setTimeout: function(callback, time) {
            var timer = Components.classes["@mozilla.org/timer;1"]
                .createInstance(Components.interfaces.nsITimer);
            timer.initWithCallback(callback, time, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
            timers.push(timer);
        }
    };

    var root = Components.classes["@mozilla.org/file/local;1"].
        createInstance(Components.interfaces.nsILocalFile);
    root.initWithPath(topsrcDir + '/tests');
    var filesEnum = root.directoryEntries, files = [];

    while (filesEnum.hasMoreElements()) {
        files.push(filesEnum.getNext().
                   QueryInterface(Components.interfaces.nsILocalFile).path);
    }

    eval(getContents("file://" + topsrcDir + "/tests/utils/testSuiteApi.js"));
    eval("var credentials = " + getContents("file://" + topsrcDir + "/tests/site-credentials") + ";");

    for (var i in credentials) {
        var site = credentials[i];
        for (var n in site.url) {
            var browser = new TestSuiteAPI(new Backend(), "file://" + topsrcDir + "/tests/" + site.test, site.login, site.password, site.url[n]);
        }
        timers.push(browser);
    }

    controller.sleep(1000 * 60);
}
