/* ***** 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 JavaScript component template.
 *
 * 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 xeITextDocumentWrapper      = C_i.xeITextDocumentWrapper;
const xeIDocumentWrapper          = C_i.xeIDocumentWrapper;
const xeIXMLDocumentWrapper       = C_i.xeIXMLDocumentWrapper;
const xeIVirtualFile              = C_i.xeIVirtualFile;
const xeIDocumentFile             = C_i.xeIDocumentFile;
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;
}

/* Begin component code. */

function JSDocumentWrapper()
{
  // xeITextDocumentWrapper
  this.selectionStartIndex = 0;

  // xeITextDocumentWrapper
  this.selectionEndIndex = 0;

  this._ownerDocumentPack = null;
  this._docFileObj = null;
  this._baseURIMap = null;
  this._pathToDocument = "";
  this._txmgr = null;
  this._pendingAction = null;
  this._txlistener = null;

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

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

  // xeITextDocumentWrapper
  reparseSource: function reparseSource(aSource) {
    this._docFileObj.contents = aSource;
  },

  // xeIDocumentWrapper
  rootLanguageType: "JavaScript",

  // xeIDocumentWrapper
  get baseURIMap() {
    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: function initializeByFile(aLocalPath, aDocumentPack) {
    this.checkNotInitialized();
    assert(aLocalPath, "No local path?");
    assert(aDocumentPack, "No document pack?");

    this._baseURIMap = aDocumentPack.getBaseURI(aLocalPath);
    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!");

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

    this._docFileObj = docFileObj;

    // Verify the file has 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/javascript";
    if (!(languageClass in Components.classes)) {
      throw new Error("No JavaScript language checker service?");
    }

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

    var err = checker.getFirstSyntaxError(this);
    if (err) {
      dump(err.errorMessage + "\n");
      throw new Error("JavaScript syntax error detected!");
    }
    */

    this._ownerDocumentPack = aDocumentPack;
    this._txmgr = aDocumentPack.txmgr;
    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 + "text/plain"]
                             .createInstance(xeIDocumentFile);
      docFileObj.init(aLocalPath, "application/javascript");
    } else {
      docFileObj = this._docFileObj;
    }

    var contents = this.wrappedSource;
    docFileObj.write(contents + "\n");
    this._docFileObj = docFileObj;
  },

  // xeIVirtualFile
  get wrappedSource() {
    this.checkInitialized();
    var contents = this._docFileObj.contents;
    return contents;
  },

  // xeIVirtualFile
  get contentType() {
    this.checkInitialized();
    return "application/javascript";
  },

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

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

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

  // nsIClassInfo
  classDescription: "JavaScript document wrapper",

  // nsIClassInfo
  classID: Components.ID("939e7c59-e726-4f51-8094-8e0fae036659"),

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

  // nsIClassInfo
  implementationLanguage: nsIProgrammingLanguage.JAVASCRIPT,

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

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

    // Known interfaces we don't support
    if (aIID.equals(xeIXMLDocumentWrapper) ||
        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: JSDocumentWrapper " + prop + "\n");
        break;
      }
    }
    if (!found) {
      dump("QUERYINTERFACE: JSDocumentWrapper Unknown\n");
    }
    throw Components.results.NS_ERROR_NO_INTERFACE;
    return null;
  }
};

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

/* Factories in modules cause leaks according to
   https://bugzilla.mozilla.org/show_bug.cgi?id=168411#c28
 */
