/* ***** 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 XML Document Wrapper.
 *
 * 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 ***** */

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

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

var componentName = "xeIXMLDocumentWrapper";
var componentId   = Components.ID("{22e190f1-52ba-4ea1-a922-29fdffd34547}");
var contractId    = "@verbosio.mozdev.org/document-wrappers/generic-xml;1";

var C_i = Components.interfaces;

const xeIXMLDocumentFile          = C_i.xeIXMLDocumentFile;
const xeIDocumentFile             = C_i.xeIDocumentFile;
const xeIVerbosioUtilsService     = C_i.xeIVerbosioUtilsService;
const nsIDOMParser                = C_i.nsIDOMParser;
const nsIDOMSerializer            = C_i.nsIDOMSerializer;
const mozIJSSubScriptLoader       = C_i.mozIJSSubScriptLoader;
const nsITransactionListener      = C_i.nsITransactionListener;
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;

C_i = null;

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

var verbosioUtils = null;

function XMLDocumentWrapper() {
  loadDebugging();
  if (!verbosioUtils) {
    verbosioUtils = Components.classes["@verbosio.mozdev.org/verbosio-utils;1"]
                              .getService(xeIVerbosioUtilsService);
  }

  this._docFileObj     = null;
  this._selectionRange = null;
  this._txmgr          = null;
  this._pendingAction  = null;
  this._documentType = null;

  // xeIDocumentWrapper
  this.baseURIMap = null;

  // xeIDocumentWrapper
  this.pathToDocument = null;

  // xeIDocumentWrapper
  this.descendantIndexes = {};

  // xeIDocumentWrapper
  this.baseURIMap = null;

  this._isInitialized = false;
}
XMLDocumentWrapper.prototype = {
  // xeIXMLDocumentWrapper
  get wrappedDocument() {
    return (this._docFileObj) ? this._docFileObj.contentDocument : null;
  },

  // xeIXMLDocumentWrapper
  get selectionRange() {
    return this._selectionRange;
  },

  // xeIXMLDocumentWrapper
  get documentType() {
    return this._documentType;
  },
  set documentType(val) {
    if (this.txlistener.inTransaction < 1) {
      ERROR_FAILURE();
    }

    if (!this.wrappedDocument.documentElement) {
      ERROR_FAILURE();
    }

    var tagName = this.wrappedDocument.documentElement.nodeName;
    if (val.indexOf("<!DOCTYPE " + tagName) != 0) {
      ERROR_FAILURE();
    }

    this._documentType = val;
    return val;
  },

  // xeIDocumentWrapper
  get rootLanguageType() {
    // This is a generic XML file.
    return "XML";
  },

  // xeIDocumentWrapper
  get txmgr() {
    return this._txmgr;
  },

  // xeIDocumentWrapper
  get pendingAction() {
    return this._pendingAction;
  },

  // xeIDocumentWrapper
  set pendingAction(aPendingAction) {
    /* XXX ajvincent When this document is part of a document pack, the
     * pending action will have an ownerWrapper property that isn't this.
     */
    this._pendingAction = aPendingAction;
  },

  // xeIDocumentWrapper
//*
  txlistener: ({
    inTransaction: 0,

    willDoTransaction: function willDoTransaction(aMgr, aTxn) {
      this.inTransaction++;
    },
    didDoTransaction: function didDoTransaction(aMgr, aTxn, aResult) {
      this.inTransaction--;
    },
    willUndoTransaction: function willUndoTransaction(aMgr, aTxn) {
      this.inTransaction++;
    },
    didUndoTransaction: function didUndoTransaction(aMgr, aTxn, aResult) {
      this.inTransaction--;
    },
    willRedoTransaction: function willRedoTransaction(aMgr, aTxn) {
      this.inTransaction++;
    },
    didRedoTransaction: function didRedoTransaction(aMgr, aTxn, aResult) {
      this.inTransaction--;
    },
    willBeginBatch: function willBeginBatch(aMgr) {
    },
    didBeginBatch: function didBeginBatch(aMgr, aResult) {
    },
    willEndBatch: function willEndBatch(aMgr) {
    },
    didEndBatch: function didEndBatch(aMgr, aResult) {
    },
    willMerge: function willMerge(aMgr, aTopTxn, aMergeTxn) {
    },
    didMerge: function didMerge(aMgr, aTopTxn, aMergeTxn, aDidMerge, aResult) {
    },

    QueryInterface: function QueryInterface(aIID) {
      if (aIID.equals(nsITransactionListener) ||
          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 XMLDocumentWrapper.txlistener: " + prop + "\n");
          break;
        }
      }
      if (!found) {
        dump("QUERYINTERFACE XMLDocumentWrapper.txlistener: Unknown\n");
      }
      throw Components.results.NS_ERROR_NO_INTERFACE;
      return null;
    }
  }), // end XMLDocumentWrapper.prototype.txlistener
// txlistener: null,

  // xeIDocumentWrapper
  get defaultViewerID() {
    return null;
  },

  // xeIDocumentWrapper
  get preconditionLocalId() {
    return null;
  },

  // xeIDocumentWrapper
  initializeByPrecondition: function initBy(aPrecondition) {
    if (this._isInitialized) {
      throw new Error("Document wrapper was already initialized!");
    }

    NOT_IMPLEMENTED();

    this._isInitialized = true;
  },

  // xeIDocumentWrapper
  initializeByFile: function initializeByFile(aLocalPath, aBaseURI) {
    if (this._isInitialized) {
      throw new Error("Document wrapper was already initialized!");
    }

    var docFileClass = "@verbosio.mozdev.org/document-file;1?contentType=";
    var docFileObj = Components.classes[docFileClass + "application/xml"]
                               .createInstance(xeIXMLDocumentFile);
    docFileObj.init(aLocalPath, "application/xml");
    docFileObj.read();

    this._docFileObj = docFileObj;

    // Verify the file is well-formed XML (no syntax errors!)
    var languageClass = "@verbosio.mozdev.org/language-pack-service;1";
    languageClass += "?contentType=application/xml";
    if (!(languageClass in Components.classes)) {
      throw new Error("No XML language checker service?");
    }

    var xeILanguagePackService = Components.interfaces.xeILanguagePackService;
    var checker = Components.classes[languageClass]
                            .getService(xeILanguagePackService);
    if (!checker) {
      throw new Error("No XML language pack created?")
    }

    var err = checker.getFirstSyntaxError(this);
    if (err) {
      dump(err.errorMessage + "\n");
      throw new Error("XML document is not well-formed!");
    }

    // Start setting up the wrapper.

    var source = docFileObj.savedContents;
    var dtdStartIndex = source.indexOf("<!DOCTYPE ");
    if (dtdStartIndex != -1) {
      this._documentType = verbosioUtils.getDTDFragment(source, dtdStartIndex);
      dump("docType: " + this._documentType + "\n");
    }

    this._selectionRange = docFileObj.contentDocument.createRange();

    const nsITxMgr = Components.interfaces.nsITransactionManager;
    const nsITxMgrCID = "@mozilla.org/transactionmanager;1";
    var txmgrClass = Components.classes[nsITxMgrCID];
    this._txmgr = txmgrClass.createInstance(nsITxMgr);

    // xeIDocumentWrapper
    if (aBaseURI) {
      this.baseURIMap = aBaseURI;
    } else {
      this.baseURIMap = Components.classes["@verbosio.mozdev.org/base-uri-map;1"]
                                  .createInstance(Components.interfaces.xeIBaseURIMap);
    }

    // Base URI map will take care of pathToDocument.
    this.baseURIMap.registerWrapper(this);
    this._isInitialized = true;
  },

  // xeIDocumentWrapper
  save: function save(aLocalPath) {
    var docFileObj = null;
    if (aLocalPath) {
      var docFileClass = "@verbosio.mozdev.org/document-file;1?contentType=";
      docFileObj = Components.classes[docFileClass + "application/xml"]
                             .createInstance(xeIXMLDocumentFile);
      docFileObj.init(aLocalPath, "application/xml");
      docFileObj.contentDocument = this.contentDocument;
    } else {
      docFileObj = this._docFileObj;
    }

    var contents = this.wrappedSource;
    var doctypeIndex = contents.indexOf("<!DOCTYPE ");
    if (doctypeIndex != -1) {
      var fragment1 = contents.substr(0, doctypeIndex);
      var dtdString = verbosioUtils.getDTDFragment(contents, doctypeIndex);
      var fragment3 = contents.substr(doctypeIndex + dtdString.length);
      contents = fragment1 + this.documentType + fragment3;
    }

    docFileObj.write(contents + "\n");

    if (aLocalPath) {
      this.baseURIMap.unregisterWrapper(this);
    }

    this._docFileObj = docFileObj;

    if (aLocalPath) {
      this.baseURIMap.registerWrapper(this);
    }

    this.txmgr.clear();
  },

  // xeIVirtualFile
  get wrappedSource() {
    if (!this._docFileObj) {
      return null;
    }
    var contents = this._docFileObj.contents;
    /* XXX ajvincent The XML serializer, which contents comes from, messes
       up a LOT of the original source formatting.  Examples:
       > Doctypes:  External entities end up as part of the internal subset.
       > White space within tags (<foo     bar="baz"/>) reduces to one space.
       > Internal entities (&FOO_NS;) are resolved in the document.
     */
    return contents;
  },

  // xeIVirtualFile
  get contentType() {
    return "application/xml";
  },

  // xeIVirtualFile
  get publicURI() {
    return (this._docFileObj) ? this._docFileObj.location : null;
  },

  // nsIClassInfo
  getInterfaces: function getInterfaces(aCount) {
    var interfaces = [Components.interfaces.xeIXMLDocumentWrapper,
                      Components.interfaces.xeIDocumentWrapper,
                      Components.interfaces.xeIVirtualFile,
                      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: 0,

  // nsISupports
  QueryInterface: function QueryInterface(aIID)
  {
    if (aIID.equals(Components.interfaces.xeIXMLDocumentWrapper) ||
        aIID.equals(Components.interfaces.xeIDocumentWrapper) ||
        aIID.equals(Components.interfaces.xeIVirtualFile) ||
        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;
        dump("QUERYINTERFACE XMLDocumentWrapper: " + prop + "\n");
        break;
      }
    }
    if (!found) {
      dump("QUERYINTERFACE XMLDocumentWrapper: 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(Components.interfaces.nsIComponentRegistrar);
    compReg.registerFactoryLocation(componentId,
                                    componentName,
                                    contractId,
                                    fileSpec,
                                    location,
                                    type );
  },

  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 XMLDocumentWrapper()).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;
    return null;
  }
};

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