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

/* Begin static code. */

// 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 xeIDocumentWrapper          = C_i.xeIDocumentWrapper;
const xeIXMLDocumentWrapper       = C_i.xeIXMLDocumentWrapper;
const xeIVirtualFile              = C_i.xeIVirtualFile;
const xeIXMLDocumentFile          = C_i.xeIXMLDocumentFile;
const xeIDTDWrapper               = C_i.xeIDTDWrapper;
const xeILanguagePackService      = C_i.xeILanguagePackService;
const xeIVerbosioUtilsService     = C_i.xeIVerbosioUtilsService;
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 verbosioUtils;

var Module = {
  factoriesByClassId: {},

  constructorsArray: [],

  addConstructor: function addConstructor(aConstructor) {
    var cid = aConstructor.prototype.classID.toString();
    this.factoriesByClassId[cid] = {
      createInstance: function createInstance(outer, iid) {
        loadSubscripts();
        if (outer != null)
          throw Components.results.NS_ERROR_NO_AGGREGATION;
        var component = new aConstructor();
        var ecmaDebug = getDebugPref();
        var retval = ecmaDebug ?
                     new InvariantContract(component) :
                     component;
        return retval.QueryInterface(iid);
      }
    };

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

  categoriesArray: [],

  addCategory: function addCategory(aCategory, aEntryName, aEntryValue) {
    this.categoriesArray[this.categoriesArray.length] = {
      category: aCategory,
      name: aEntryName,
      value: aEntryValue
    };
  },

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

    var i;
    for (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);
    }
  },

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

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

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

function loadSubscripts() {
  if (subscriptsLoaded) {
    return;
  }

  verbosioUtils = Components.classes["@verbosio.mozdev.org/verbosio-utils;1"]
                            .getService(xeIVerbosioUtilsService);
  subscriptsLoaded = true;
}

function DocumentWrapper()
{
  this._docFileObj = null;

  this._wrappedDocument = null;
  this._ownerDocumentPack = null;
  this._subsetWrapper = null;
  this._selectionRange = null;
  this._documentType = "";
  this._baseURIMap = null;
  this._pathToDocument = "";
  this._txmgr = null;
  this._pendingAction = null;

  const entityClass = "@verbosio.mozdev.org/dtd-entity-manager;1";
  this._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;
    }
  });

  this._isInitialized = false;
}
DocumentWrapper.prototype =
{
  checkInitialized: function checkInitialized() {
    if (!this._isInitialized) {
      dumpJSStack();
      NOT_INITIALIZED();
    }
  },

  checkNotInitialized: function checkNotInitialized() {
    if (this._isInitialized) {
      dumpJSStack();
      ALREADY_INITIALIZED();
    }
  },

  // Design-by contract invariant
  invariant: function invariant() {
    if (this._isInitialized) {
      assert(this.wrappedDocument, "No wrapped document?");
      assert(this.selectionRange, "No selection range?");
      assert(this.pathToDocument, "No path to document?");
      assert(this.txmgr, "No transaction manager?");
      assert(this.wrappedSource, "No wrapped source?");
      assert(this.publicURI, "No public URI?");
    }
  },

  // xeIXMLDocumentWrapper
  get wrappedDocument() {
    this.checkInitialized();
    return (this._docFileObj) ? this._docFileObj.contentDocument : null;
  },

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

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

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

  // xeIXMLDocumentWrapper
  get subsetWrapper() {
    return this._subsetWrapper;
  },

  // xeIDocumentWrapper
  rootLanguageType: "XUL",

  // xeIDocumentWrapper
  get baseURIMap() {
    // commented out for DTD handling.
    //this.checkInitialized();
    return this._baseURIMap;
  },

  // xeIDocumentWrapper
  get pathToDocument() {
    this.checkInitialized();
    return this._pathToDocument;
  },

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

  // xeIDocumentWrapper
  get txlistener() {
    this.checkInitialized();
    return this._txlistener;
  },

  // xeIDocumentWrapper
  get pendingAction() {
    this.checkInitialized();
    return this._pendingAction;
  },
  set pendingAction(val) {
    this.checkInitialized();
    this._pendingAction = val;
  },

  // xeIDocumentWrapper
  get defaultViewerID() {
    NOT_IMPLEMENTED();
  },

  // xeIDocumentWrapper
  get descendantIndexes() {
    NOT_IMPLEMENTED();
  },

  // xeIDocumentWrapper
  get preconditionLocalId() {
    NOT_IMPLEMENTED();
  },

  // xeIDocumentWrapper
  initializeByPrecondition: NOT_IMPLEMENTED,

  // xeIDocumentWrapper
  initializeByFile: getContractFunction({
    precondition: function initializeByFile_pre(aLocalPath, aPack) {
      assert(aLocalPath, "No local path?");
      assert(aPack, "No document pack?");
    },

    body: function initializeByFile(aLocalPath, aPack) {
      this.checkNotInitialized();

      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!)
      /* XXX ajvincent We need to set up the wrapper and handle errors later.
      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 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.  First, DTD handling.
      var source = docFileObj.savedContents;
      this._documentType = verbosioUtils.getDTDFragment(source);
      var doctype = this._documentType;
      this._baseURIMap = aPack.getBaseURI(aLocalPath);
      if (doctype) {
        const typeClass = "@verbosio.mozdev.org/dtd-subset-wrapper/gecko;1";
        this._subsetWrapper = Components.classes[typeClass]
                                        .createInstance(xeIDTDWrapper);
        if (doctype.indexOf("[") != -1) {
          var subset = doctype.substring(doctype.indexOf("[") + 1,
                                         doctype.indexOf("]") - 1);
          this._subsetWrapper.parseDTD(subset, this, aPack);
        }
      }

      // Now generate the XML document.
      docFileObj.parse(this, aPack);

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

      this._ownerDocumentPack = aPack;
      this._txmgr = aPack.txmgr;

      var localBase = this._baseURIMap.getURI("local");
      assert(aLocalPath.indexOf(localBase) == 0, "Local base URI didn't match?");
      assert(aLocalPath.length > localBase.length, "Local base URI is too long!");
      this._pathToDocument = aLocalPath.substr(localBase.length);

      this._isInitialized = true;
    }
  }),

  // xeIDocumentWrapper
  save: function save(aLocalPath) {
    this.checkInitialized();
    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 entityMgr = this._ownerDocumentPack.entityManager;
    var contents = entityMgr.getSanitizedContent(this);
    if (getDebugPref() && this.documentType) {
      var doctypeFragment = verbosioUtils.getDTDFragment(contents);
      assert(doctypeFragment, "No document type?  What are we smoking?");
    }
    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() {
    this.checkInitialized();
    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() {
    this.checkInitialized();
    return "application/vnd.mozilla.xul+xml";
  },

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

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

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

  // nsIClassInfo
  classDescription: "XUL document wrapper",

  // nsIClassInfo
  classID: Components.ID("6a291d18-0db7-4db7-992d-54a52a7dd873"),

  // nsIClassInfo
  contractID: "@verbosio.mozdev.org/document-wrappers/xul;1?version=1.0",

  // nsIClassInfo
  implementationLanguage: nsIProgrammingLanguage.JAVASCRIPT,

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

  // nsISupports
  QueryInterface: function QueryInterface(aIID) {
    if (aIID.equals(xeIXMLDocumentWrapper) ||
        aIID.equals(xeIDocumentWrapper) ||
        aIID.equals(xeIVirtualFile) ||
        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: DocumentWrapper " + prop + "\n");
        break;
      }
    }
    if (!found) {
      dump("QUERYINTERFACE: DocumentWrapper Unknown\n");
    }

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

Module.addConstructor(DocumentWrapper);
Module.addCategory("Verbosio document wrappers by file type",
                   "xul",
                   DocumentWrapper.prototype.contractID);
