/* ***** 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 Verbosio CSS Language Pack.
 *
 * The Initial Developer of the Original Code is
 * Alexander J. Vincent <ajvincent@gmail.com>.
 * Portions created by the Initial Developer are Copyright (C) 2007
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * 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 ***** */

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

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

// Utility function.
function ERROR_ABORT() {
  throw Components.results.NS_ERROR_ABORT;
}

// Utility function
function NOT_INITIALIZED() {
  throw Components.results.NS_ERROR_NOT_INITIALIZED;
}

// Utility function
function ALREADY_INITIALIZED() {
  throw Components.results.NS_ERROR_ALREADY_INITIALIZED;
}

const C_i = Components.interfaces;

const xeILanguagePackService      = C_i.xeILanguagePackService;
const mozIJSSubScriptLoader       = C_i.mozIJSSubScriptLoader;
const nsICategoryManager          = C_i.nsICategoryManager;
const nsIScriptError              = C_i.nsIScriptError;
const nsIProgrammingLanguage      = C_i.nsIProgrammingLanguage;
const nsISecurityCheckedComponent = C_i.nsISecurityCheckedComponent;
const nsIClassInfo                = C_i.nsIClassInfo;
const nsIComponentRegistrar       = C_i.nsIComponentRegistrar;
const nsIFactory                  = C_i.nsIFactory;
const nsIModule                   = C_i.nsIModule;
const nsISupports                 = C_i.nsISupports;

var Module = {
  factoriesByClassId: {},

  constructorsArray: [],

  /**
   * Add a component constructor to the module.
   *
   * @param aConstructor JavaScript function implementing nsIClassInfo
   */
  addConstructor: function addConstructor(aConstructor) {
    var cid = aConstructor.prototype.classID.toString();
    this.factoriesByClassId[cid] = {
      createInstance: function createInstance(outer, iid) {
        if (outer != null)
          throw Components.results.NS_ERROR_NO_AGGREGATION;
        return (new aConstructor()).QueryInterface(iid);
      }
    };

    this.constructorsArray[this.constructorsArray.length] = aConstructor;
  },

  categoriesArray: [],

  /**
   * Add a category for the category manager to accept at registration time.
   *
   * @param aCategory   The category to add.
   * @param aEntryName  The name of the entry.
   * @param aEntryValue The value of the entry (usually a component class id).
   */
  addCategory: function addCategory(aCategory, aEntryName, aEntryValue) {
    this.categoriesArray[this.categoriesArray.length] = {
      category: aCategory,
      name: aEntryName,
      value: aEntryValue
    };
  },

  // nsIModule
  registerSelf: function registerSelf(compMgr, fileSpec, location, type) {
    compReg = compMgr.QueryInterface(nsIComponentRegistrar);

    for (var i = 0; i < this.constructorsArray.length; i++) {
      var proto = this.constructorsArray[i].prototype;
      compReg.registerFactoryLocation(proto.classID,
                                      proto.classDescription,
                                      proto.contractID,
                                      fileSpec,
                                      location,
                                      type);
    }

    if (!this.categoriesArray.length) {
      return;
    }
    var catman = Components.classes["@mozilla.org/categorymanager;1"]
                           .getService(nsICategoryManager);
    for (i = 0; i < this.categoriesArray.length; i++) {
      var entry = this.categoriesArray[i];
      catman.addCategoryEntry(entry.category,
                              entry.name,
                              entry.value,
                              true,
                              true);
    }
  },

  // nsIModule
  getClassObject: function getClassObject(compMgr, aCID, aIID) {
    if (!aIID.equals(nsIFactory)) {
      throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
    }

    for (var prop in this.factoriesByClassId) {
      if (aCID.equals(Components.ID(prop))) {
        loadSubscripts();
        return this.factoriesByClassId[prop];
      }
    }
    throw Components.results.NS_ERROR_NO_INTERFACE;
  },

  // nsIModule
  canUnload: function canUnload() {
    return true;
  },

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

    throw Components.results.NS_ERROR_NO_INTERFACE;
    return null;
  }
};

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

var subscriptsLoaded = false;
function loadSubscripts() {
  if (subscriptsLoaded) {
    return;
  }
  var jsLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
                           .getService(mozIJSSubScriptLoader);
  jsLoader.loadSubScript("resource://app/res/ecma-debug.js");
  subscriptsLoaded = true;
}

function CSSLanguagePack()
{
}
CSSLanguagePack.prototype =
{
  // xeILanguagePackService
  contentType: "text/css",

  // xeILanguagePackService
  specificationURI: "http://www.w3.org/Style/CSS/#specs",

  // xeILanguagePackService
  description: "Cascading Style Sheets",

  // xeILanguagePackService
  id: "CSS",

  // xeILanguagePackService
  version: "2.1",

  // xeILanguagePackService
  getNewTransaction: NOT_IMPLEMENTED,

  getFirstSyntaxError: NOT_IMPLEMENTED,

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

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

  // nsIClassInfo
  classDescription: "Language Checker Service, CSS",

  // nsIClassInfo
  classID: Components.ID("{b81127db-f593-4737-a3d6-ab5805c91ab4}"),

  // nsIClassInfo
  contractID: "@verbosio.mozdev.org/language-pack-service;1?" +
              "contentType=text/css",

  // nsIClassInfo
  implementationLanguage: nsIProgrammingLanguage.JAVASCRIPT,

  // nsIClassInfo
  flags: 0, /* nsIClassInfo.SINGLETON for services */

  // nsISupports
  QueryInterface: function QueryInterface(aIID) {
    if (aIID.equals(xeILanguagePackService) ||
        aIID.equals(nsIClassInfo) ||
        aIID.equals(nsISupports))
      return this;

    // Known interfaces we don't support.
    if (aIID.equals(nsISecurityCheckedComponent)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
      return null;
    }

    // Discover what interfaces we need
    var i = Components.interfaces;
    var found = false;
    for (var prop in i) {
      if (aIID.equals(i[prop])) {
        found = true;
        dump("QUERYINTERFACE: CSSLanguagePack " + prop + "\n");
        break;
      }
    }
    if (!found) {
      dump("QUERYINTERFACE: CSSLanguagePack Unknown\n");
    }
    throw Components.results.NS_ERROR_NO_INTERFACE;
    return null;
  }
};

Module.addConstructor(CSSLanguagePack);
