// vim: ts=2 sw=2 expandtab cindent
//
// 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
//

const CONTRACT_ID = "@flock.com/singleton;1";
const CLASS_ID = Components.ID("{df938052-196a-429a-88b5-f72af6b56689}");
const CLASS_NAME = "Flock JavaScript Singleton Service";

const CC = Components.classes;
const CI = Components.interfaces;
const CR = Components.results;
const CU = Components.utils;

CU.import("resource:///modules/FlockXPCOMUtils.jsm");


function SingletonService() {
  this._instances = {};
  this._loader = CC["@mozilla.org/moz/jssubscript-loader;1"]
                 .getService(CI.mozIJSSubScriptLoader);
}

SingletonService.prototype = new FlockXPCOMUtils.genericComponent(
  CLASS_NAME,
  CLASS_ID,
  CONTRACT_ID,
  SingletonService,
  CI.nsIClassInfo.SINGLETON,
  [CI.flockISingleton]
);

SingletonService.prototype.getSingleton =
function SS_getSingleton(aURI)
{
  if (!this._instances[aURI]) {
    if (aURI.indexOf("hash:") == 0) {
      this._instances[aURI] = {};
    } else if (aURI.indexOf("array:") == 0) {
      this._instances[aURI] = [];
    } else {
      // we need to load the script
      var context = {};

      // load the script
      this._loader.loadSubScript(aURI, context);

      // see if we should use a specific object instead of the script context
      if (context.__singleton__) {
        this._instances[aURI] = context.__singleton__;
      } else {
        this._instances[aURI] = context;
      }
    }
  } 

  return { wrappedJSObject: this._instances[aURI] };
}

var gComponentsArray = [SingletonService];

var NSGetModule = FlockXPCOMUtils.generateNSGetModule(CLASS_NAME,
                                                      gComponentsArray);
