// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2009
// http://flock.com
//
// This file may be used under the terms of the
// GNU General Public License Version 2 or later (the "GPL"),
// http://www.gnu.org/licenses/gpl.html
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// END FLOCK GPL

function flock_QuickTest() {
  const DEFAULT_TEST_FILE = "file:///tmp/quicktest.js";

  const CC = Components.classes;
  const CI = Components.interfaces;

  if (document.referrer) {
     return;
  }

  var filenames = [ DEFAULT_TEST_FILE ];

  var url = document.documentURI;
  var index = url.indexOf('?');
  if (index != -1) {
    var fileList = url.substr(index + 1);
    filenames = fileList.split("&");
  }

  var loader = CC["@mozilla.org/moz/jssubscript-loader;1"]
               .getService(CI.mozIJSSubScriptLoader);

  var ios = CC["@mozilla.org/network/io-service;1"]
            .getService(CI.nsIIOService);
  var fh = ios.getProtocolHandler("file")
              .QueryInterface(CI.nsIFileProtocolHandler);

  function makeFileURL(aFilename) {
    if (aFilename.indexOf("file:") != 0) {
      var file = CC["@mozilla.org/file/local;1"]
                 .createInstance(CI.nsILocalFile);
      file.initWithPath(aFilename);
      return fh.getURLSpecFromFile(file);
    } else {
      return aFilename;
    }
  }

  function getScriptList(aFilename) {
    var file = fh.getFileFromURLSpec(aFilename);
    if (!file.exists()) {
      return [];
    }

    var fis = CC["@mozilla.org/network/file-input-stream;1"]
              .createInstance(CI.nsIFileInputStream);
    fis.init(file, 0x01 /* PR_RDONLY */, 0, 0);

    var sis = CC["@mozilla.org/scriptableinputstream;1"]
              .createInstance(CI.nsIScriptableInputStream);
    sis.init(fis);

    var data = sis.read(sis.available());
    sis.close();

    var scriptList = [], list = data.split("\n");
    for (var i = 0; i < list.length; i++) {
      var filename = list[i];
      filename = filename.replace("\r", "");
      if (filename) {
        scriptList.push(makeFileURL(filename));
      }
    }

    return scriptList;
  }

  for (var i = 0; i < filenames.length; i++) {
    var filename = makeFileURL(decodeURIComponent(filenames[i]));

    var scriptFiles;
    if (filename.match(/\.jslist$/)) {
      scriptFiles = getScriptList(filename);
    } else {
      scriptFiles = [ filename ];
    }

    scriptFiles.forEach(loader.loadSubScript, {});
  }
}
