/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * 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.
 *
 * The Original Code is ManyOne Chrome Messenger.
 *
 * The Initial Developer of the Original Code is
 * Alexander J. Vincent <ajvincent@gmail.com>.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *  The ManyOne Networks, Inc. Development Team
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

// Component metadata.  Please change all the values in this section.

var componentName = "mnIChromeMessenger";
var componentId   = Components.ID("{093a9623-a810-4dd0-99a0-63d520e2b957}");
var contractId    = "@manyone.net/chrome-messenger;1";

// Utility function.
function ERROR_FAILURE() {
  throw Components.results.NS_ERROR_FAILURE;
}

// Utility function.
function NOT_IMPLEMENTED() {
  throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
}

var mObserverService = Components.classes["@mozilla.org/observer-service;1"]
                                 .getService(Components.interfaces.nsIObserverService);
//var mConsoleService  = Components.classes["@mozilla.org/consoleservice;1"]
//                                 .getService(Components.interfaces.nsIConsoleService);

function logError(aMsg) {
  //mConsoleService.logStringMessage("chromeMessenger: " + aMsg + "\n");
  debug("chromeMessenger: " + aMsg + "\n");
  ERROR_FAILURE();
}

// Chrome messenger object constructor.
function chromeMessenger() {
}
chromeMessenger.prototype = {
  // mnIChromeMessenger
  send: function send(aSubject) {
    if (!(aSubject instanceof Components.interfaces.nsISupports)) {
      logError("aData isn't implementing nsISupports!  This is really bad!");
    }

    if (!aSubject.wrappedJSObject) {
      logError("aData must have a wrappedJSObject property.");
    }

    var subject = aSubject.wrappedJSObject;

    for (var prop in subject) {
      var propObj = subject[prop];
      debug("Checking " + prop + "\n");
      switch (prop) {
        case "wrappedJSObject":
        case "QueryInterface":
          continue;

        case "window":
          if (!(propObj instanceof Components.interfaces.nsIDOMWindow)) {
            logError("aData.window must be a window object.");
          }

          continue;
      }

      switch (typeof propObj) {
        case "number":
        case "string":
        case "boolean":
        case "undefined":
          continue;

        default:
          logError("aData." + prop + " must be of type number, string, boolean, or undefined.");
      }
    }

    mObserverService.notifyObservers(aSubject, "content-message", null);
  },

  // nsISecurityCheckedComponent
  canCreateWrapper: function canCreateWrapper(iid)
  {
    return "AllAccess";
  },

  // nsISecurityCheckedComponent
  canCallMethod: function canCallMethod(iid)
  {
    return "AllAccess";
  },

  // nsISecurityCheckedComponent
  canGetProperty: function canGetProperty(iid)
  {
    return "AllAccess";
  },

  // nsISecurityCheckedComponent
  canSetProperty: function canSetProperty(iid)
  {
    return "NoAccess";
  },

  // nsIClassInfo
  getInterfaces: function getInterfaces(aCount) {
    var interfaces = [Components.interfaces.mnIChromeMessenger,
                      Components.interfaces.nsISecurityCheckedComponent,
                      Components.interfaces.nsIClassInfo];
    aCount.value = interfaces.length;
    return interfaces;
  },

  // nsIClassInfo
  getHelperForLanguage: function getHelperForLanguage(aLanguage) {
    return null;
  },

  // nsIClassInfo
  contractID: contractId,

  // nsIClassInfo
  classDescription: componentName,

  // nsIClassInfo
  classID: componentId,

  // nsIClassInfo
  implementationLanguage: Components.interfaces.nsIProgrammingLanguage.JAVASCRIPT,

  // nsIClassInfo
  flags: Components.interfaces.nsIClassInfo.SINGLETON,

  // nsISupports
  QueryInterface: function QueryInterface(aIID) {
    if (aIID.equals(Components.interfaces.mnIChromeMessenger) ||
        aIID.equals(Components.interfaces.nsISecurityCheckedComponent) ||
        aIID.equals(Components.interfaces.nsIClassInfo) ||
        aIID.equals(Components.interfaces.nsISupports))
      return this;

    // Discover what interfaces we need
    var i = Components.interfaces;
    var found = false;
    for (var prop in i) {
      if (aIID.equals(i[prop])) {
        found = true;
        debug("QUERYINTERFACE mnChromeMessenger.js: " + prop + "\n");
        break;
      }
    }
    if (!found) {
      debug("QUERYINTERFACE mnChromeMessenger.js: Unknown\n");
    }

    debug("iid: " + aIID + "\n");
  }
};

/* The rest of this code is largely borrowed from "Creating Applications With
 * Mozilla", http://books.mozdev.org, Chapter 8.
 */
var Module = {
  registerSelf: function registerSelf(compMgr, fileSpec, location, type) {
    compReg = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
    compReg.registerFactoryLocation(componentId,
                                    componentName,
                                    contractId,
                                    fileSpec,
                                    location,
                                    type );

    // Add chromeMessenger constructor
    var catman = Components.classes["@mozilla.org/categorymanager;1"]
                           .getService(Components.interfaces.nsICategoryManager);
    catman.addCategoryEntry("JavaScript global property",
                            "chromeMessenger",
                            contractId,
                            true,  /* Persist this entry */
                            true); /* Replace existing entry */
  },

  getClassObject: function(compMgr, aCID, aIID) {
    if (!aCID.equals(componentId)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
    }
    if (!aIID.equals(Components.interfaces.nsIFactory)) {
      throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
    }
    return this.factory;
  },

  factory: {
    createInstance: function createInstance(outer, iid) {
      if (outer != null)
        throw Components.results.NS_ERROR_NO_AGGREGATION;

      return (new chromeMessenger()).QueryInterface(iid);
    }
  },

  canUnload: function() {
    return true;
  },

  QueryInterface:  function QueryInterface(aIID) {
    if (aIID.equals(Components.interfaces.nsIModule) ||
       (aIID.equals(Components.interfaces.nsISupports)))
      return this;

    throw Components.results.NS_ERROR_NO_INTERFACE;
  }
};

function NSGetModule(compMgr, fileSpec) {
  return Module;
}
