/* ***** 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 Language Checker Service, XML.
 *
 * 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):
 *
 * 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 = "Language Pack Service, generic XML";
var contractId    = "@verbosio.mozdev.org/language-pack-service;1?contentType=application/xml";
var componentId   = Components.ID("{3312b494-16f4-4631-be1f-0658984961d4}");

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

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

var C_i = Components.interfaces;

const xeIXMLLanguagePackService   = C_i.xeIXMLLanguagePackService;
const xeILanguagePackService      = C_i.xeILanguagePackService;
const nsITransactionListener      = C_i.nsITransactionListener;
const nsIScriptError              = C_i.nsIScriptError;
const nsISAXXMLReader             = C_i.nsISAXXMLReader;
const nsISecurityCheckedComponent = C_i.nsISecurityCheckedComponent;
const nsIProgrammingLanguage      = C_i.nsIProgrammingLanguage;
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;

C_i = null;

var saxReader = Components.classes["@mozilla.org/saxparser/xmlreader;1"]
                          .createInstance(nsISAXXMLReader);
var saxErrorHandler = {
  locator: null,
  error: null,

  reset: function reset() {
    this.locator = null;
    this.error   = null;
  },

  fatalError: function fatalError(locator, error)
  {
    this.locator = locator;
    this.error   = error;
  },

  error: function error(locator, error)
  {
    // do nothing
  },

  ignorableWarning: function ignorableWarning(locator, error)
  {
    // do nothing
  }
};

saxReader.errorHandler = saxErrorHandler;

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

// Language pack service constructor.
function languagePack()
{
  loadDebugging();
}
languagePack.prototype = {
  // xeIXMLLanguagePackService
  namespaceURI: "http://www.w3.org/XML/1998/namespace",

  // xeIXMLLanguagePackService
  prefix: "xml",

  // xeIXMLLanguagePackService
  getDTDUriArray: function getDTDUriArray(aCount) {
    NOT_IMPLEMENTED();
  },

  // xeIXMLLanguagePackService
  getXMLSchemaArray: function getXMLSchemaArray(aCount) {
    NOT_IMPLEMENTED();
  },

  // xeIXMLLanguagePackService
  get attributeWrapperName() {
    NOT_IMPLEMENTED();
  },

  // xeIXMLLanguagePackService
  handleWhitespace: function handleWhitespace(aLocalName) {
    return xeIXMLLanguagePackService.WHITESPACE_PRESERVE;
  },

  // xeIXMLLanguagePackService
  isURINode: function isURINode(aNode) {
    loadDebugging();

    var ownerNode = null;
    if (aNode.nodeType == nsIDOMNode.ATTRIBUTE_NODE) {
      ownerNode = aNode.ownerElement;
    }
    if (aNode instanceof nsIDOMCharacterData) {
      ownerNode = aNode.parentNode;
    }

    assert(ownerNode, "No owner element for this node?");
    assert(ownerNode.nodeType == nsIDOMNode.ELEMENT_NODE, "No owner element for this node?");

    if ((aNode.namespaceURI == XLINK_NS) &&
        (aNode.localName == "href")) {
      return true;
    }

    return false;
  },

  // xeIXMLLanguagePackService
  checkValidity: function checkValidity() {
    // XML doesn't have any validity checking.
    return null;
  },

  // xeILanguagePackService
  contentType: "application/xml",

  // xeILanguagePackService
  specificationURI: "http://www.w3.org/TR/xml/",

  // xeILanguagePackService
  description: "Generic XML",

  // xeILanguagePackService
  id: "XML",

  // xeILanguagePackService
  version: "1.0",

  // xeILanguagePackService
  getNewTransaction: function getNewTransaction(transactionName) {
    NOT_IMPLEMENTED();
  },

  // xeILanguagePackService
  getFirstSyntaxError: function hasSyntaxError(wrapper) {
    saxErrorHandler.reset();

    saxReader.parseFromString(wrapper.wrappedSource, "application/xml");

    if (saxErrorHandler.locator) {
      var scriptError = Components.classes["@mozilla.org/scripterror;1"]
                                  .createInstance(nsIScriptError);
      var lineNumber = saxErrorHandler.locator.lineNumber;
      var sourceLine = wrapper.wrappedSource.split("\n")[lineNumber - 1];

      scriptError.init(saxErrorHandler.error,
                       wrapper.publicURI,
                       sourceLine,
                       saxErrorHandler.locator.lineNumber,
                       saxErrorHandler.locator.columnNumber,
                       nsIScriptError.errorFlag,
                       null);

      return scriptError;
    }

    return null;
  },

  // nsITransactionListener
  willDo: function willDo(aManager, aTransaction) {
    // Do nothing
  },

  // nsITransactionListener
  didDo: function didDo(aManager, aTransaction, aResult) {
    // Do nothing
  },

  // nsITransactionListener
  willUndo: function willUndo(aManager, aTransaction) {
    // Do nothing
  },

  // nsITransactionListener
  didUndo: function didUndo(aManager, aTransaction, aResult) {
    // Do nothing
  },

  // nsITransactionListener
  willRedo: function willRedo(aManager, aTransaction) {
    // Do nothing
  },

  // nsITransactionListener
  didRedo: function didRedo(aManager, aTransaction, aResult) {
    // Do nothing
  },

  // nsITransactionListener
  willBeginBatch: function willBeginBatch(aManager) {
    NOT_IMPLEMENTED();
  },

  // nsITransactionListener
  didBeginBatch: function didBeginBatch(aManager, aResult) {
    NOT_IMPLEMENTED();
  },

  // nsITransactionListener
  willEndBatch: function willEndBatch(aManager) {
    NOT_IMPLEMENTED();
  },

  // nsITransactionListener
  didEndBatch: function didEndBatch(aManager, aResult) {
    NOT_IMPLEMENTED();
  },

  // nsITransactionListener
  willMerge: function willMerge(aManager, aTopTxn, aTxnToMerge) {
    NOT_IMPLEMENTED();
  },

  // nsITransactionListener
  didMerge: function didMerge(aManager, aTopTxn, aTxnToMerge) {
    NOT_IMPLEMENTED();
  },

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

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

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

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

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

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

  // nsIClassInfo
  classDescription: componentName,

  // nsIClassInfo
  classID: componentId,

  // nsIClassInfo
  contractID: contractId,

  // nsIClassInfo
  implementationLanguage: nsIProgrammingLanguage.JAVASCRIPT,

  // nsIClassInfo
  flags: nsIClassInfo.SINGLETON,

  // nsISupports
  QueryInterface: function QueryInterface(aIID) {
    if (aIID.equals(xeIXMLLanguagePackService) ||
        aIID.equals(xeILanguagePackService) ||
        aIID.equals(nsITransactionListener) ||
        aIID.equals(nsISecurityCheckedComponent) ||
        aIID.equals(nsIClassInfo) ||
        aIID.equals(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;
        dump("QUERYINTERFACE XML language pack: " + prop + "\n");
        break;
      }
    }
    if (!found) {
      dump("QUERYINTERFACE XML language pack: Unknown\n");
    }

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

/* 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(nsIComponentRegistrar);

    compReg.registerFactoryLocation(componentId,
                                    componentName,
                                    contractId,
                                    fileSpec,
                                    location,
                                    type);
  },

  getClassObject: function getClassObject(compMgr, aCID, aIID) {
    if (!aCID.equals(componentId)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
    }
    if (!aIID.equals(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 languagePack()).QueryInterface(iid);
    }
  },

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

  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;
}
