/* ***** 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 Document File components.
 *
 * 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 ***** */

// Get JS modules.
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://app/modules/ecma-debug.jsm");
Components.utils.import("resource://app/modules/XMLValidator.jsm");

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

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

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

var C_i = Components.interfaces;

const xeIDocumentWrapper          = C_i.xeIDocumentWrapper;
const xeIXMLDocumentFile          = C_i.xeIXMLDocumentFile;
const xeIDocumentFile             = C_i.xeIDocumentFile;
const xeIVirtualFileService       = C_i.xeIVirtualFileService;
const xeIDTDWrapper               = C_i.xeIDTDWrapper;
const nsIDOMParser                = C_i.nsIDOMParser;
const nsIDOMSerializer            = C_i.nsIDOMSerializer;
const nsISAXXMLReader             = C_i.nsISAXXMLReader;
const mozIJSSubScriptLoader       = C_i.mozIJSSubScriptLoader;
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;

const parser     = Components.classes["@mozilla.org/xmlextras/domparser;1"]
                             .createInstance(nsIDOMParser);
const serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"]
                             .createInstance(nsIDOMSerializer);

var virtualFS = null;

var subscriptsLoaded = false;
var jsLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
                         .getService(mozIJSSubScriptLoader);
function loadSubscripts() {
  if (subscriptsLoaded) {
    return;
  }

  jsLoader.loadSubScript("chrome://jslib/content/jslib.js");
  jsLoader.loadSubScript("chrome://jslib/content/io/io.js");

  virtualFS = Components.classes["@verbosio.mozdev.org/virtual-file-service;1"]
                        .getService(xeIVirtualFileService);
  subscriptsLoaded = true;
}

function DocumentFile()
{
  loadSubscripts();
  this.location = null;
  this.contentType = null;
  this.contents = null;
  this.savedContents = null;
  this.fileObj = null;
}
DocumentFile.prototype = {
  init: function init(location, contentType)
  {
    this.contentType = contentType;
    this.fileObj = new File(location);
    this.initialized = true;
    this.location = this.fileObj.URL;
  },

  read: function read()
  {
    if (!this.fileObj)
    {
      ERROR_ABORT();
    }

    if (!this.fileObj.exists()) {
      ERROR_ABORT();
    }

    this.fileObj.open("r");
    var contents = this.fileObj.read();
    this.fileObj.close();

    this.contents = contents;
    this.savedContents = contents;
  },

  write: function write(contents)
  {
    if (!this.fileObj)
    {
      ERROR_ABORT();
    }

    this.fileObj.open("w");
    this.fileObj.write(contents);
    this.fileObj.close();

    this.savedContents = contents;
  },

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

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

  // nsIClassInfo
  classDescription: "Verbosio Document File",

  // nsIClassInfo
  classID: Components.ID("{40a28f22-7b3f-4693-a0fe-cd40192a413f}"),

  // nsIClassInfo
  contractID: "@verbosio.mozdev.org/document-file;1?contentType=text/plain",

  // nsIClassInfo
  implementationLanguage: nsIProgrammingLanguage.JAVASCRIPT,

  // nsIClassInfo
  flags: 0,

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

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

function XMLDocumentFile()
{
  loadSubscripts();
  this.location = null;
  this.contentType = null;
  this.savedContents = null;
  this.fileObj = null;
  this.contentDocument = null;
}
XMLDocumentFile.prototype = {
  init: function init(location, contentType)
  {
    this.contentType = contentType;
    this.fileObj = new File(location);
    this.initialized = true;
    this.location = this.fileObj.URL;
  },

  read: function read()
  {
    if (!this.fileObj)
    {
      dump("No file object!");
      ERROR_ABORT();
    }

    if (!this.fileObj.exists()) {
      dump("File does not exist!");
      ERROR_ABORT();
    }

    this.fileObj.open("r");
    var contents = this.fileObj.read();
    this.fileObj.close();

    this.savedContents = contents;
  },

  get contents() {
    try {
      if (!this.contentDocument) {
        return this.savedContents;
      }
      return serializer.serializeToString(this.contentDocument,
                                          "application/xml");
    }
    catch (e) {
      dump(e.stack);
      throw e;
    }
  },

  set contents(val) {
    NOT_IMPLEMENTED();
  },

  write: function write(contents)
  {
    if (!this.fileObj)
    {
      dump("No file object!");
      ERROR_ABORT();
    }

    this.fileObj.open("w");
    this.fileObj.write(contents);
    this.fileObj.close();

    this.savedContents = contents;
  },

  noMinusOnes: function noMinusOnes(aNum) {
    return (aNum == -1) ? Infinity : aNum;
  },

  getDTDWrapper: function getDTDWrapper(aEntityName, aDTDWrapper) {
    var entityRefs = aDTDWrapper.getExternalDTDReferences({});
    var wrappers = aDTDWrapper.getExternalDTDWrappers({});
    var dtdWrapperName;
    for each (entityName in entityRefs) {
      if (aEntityName == entityName && entityName in wrappers) {
        return wrappers[entityName];
      }
    }

    for (dtdWrapperName in wrappers) {
      var retval = this.getDTDWrapper(aEntityName, wrappers[dtdWrapperName]);
      if (retval) {
        return retval;
      }
    }
    return null;
  },

  getResolvedDTD: function getResolvedDTD(aDTDWrapper) {
    var source = "";
    assert(aDTDWrapper instanceof xeIDTDWrapper, "aDTDWrapper = " + aDTDWrapper);
    var externals = aDTDWrapper.getExternalDTDWrappers({});
    for (var i = 0; i < externals.length; i++) {
      source += this.getResolvedDTD(externals[i]);
    }
    if (aDTDWrapper instanceof xeIDocumentWrapper) {
      source += aDTDWrapper.wrappedSource;
    }
    return source;
  },

  getDTDExternalEntities: function getDTDExternalEntities(aDTDWrapper) {
    var result = [];
    var entityList = aDTDWrapper.getExternalDTDReferences({});
    for (var i = 0; i < entityList.length; i++) {
      var entityValue = aDTDWrapper.getDTDRefValue(entityList[i]);
      if ((entityValue.indexOf("chrome://") == 0) &&
          (entityValue.indexOf("chrome://global/") != 0) &&
          (entityValue.indexOf("chrome://toolkit/") != 0)) {
        result[result.length] = entityList[i];
      }
    }

    var wrappers = aDTDWrapper.getExternalDTDWrappers({});
    for (i = 0; i < wrappers.length; i++) {
      result = result.concat(this.getDTDExternalEntities(wrappers[i]));
    }
    return result;
  },

  // xeIXMLDocumentFile
  parse: function parse(aWrapper, aPack) {
    var contents = this.savedContents;
    assert(typeof contents == "string", "No contents?");
    assert(contents.length > 0, "No contents?");

    // Get DTD virtual URI's and substitute
    virtualFS.setDocumentPack(aPack);
    var dtdWrapper = aWrapper.subsetWrapper;
    var doctype    = aWrapper.documentType;
    var firstPart;
    var thirdPart;
    var refIndex;
    var i;
    if (dtdWrapper) {
      assert(doctype, "No document type?");

      /* Insert dtd's imported from other sources.  This lets us bypass
         the <!ENTITY % foo SYSTEM "chrome://foo/locale/foo.dtd"> %foo;
         approach.  We can't use that approach because (a) chrome://foo/locale/
         doesn't exist in Verbosio, and (b) we can't substitute a
         virtual://chrome//foo/locale/foo.dtd URI in the SYSTEM entity.
       */
      var refs = dtdWrapper.getExternalDTDWrappers({});
      var dtdSource = "";
      for (i = 0; i < refs.length; i++) {
        dtdSource += this.getResolvedDTD(refs[i]);
      }
      refIndex = doctype.indexOf("[");
      assert(refIndex > 0, "XXX fix me");
      firstPart = doctype.substr(0, refIndex + 1);
      thirdPart = doctype.substr(refIndex + 1);
      doctype = firstPart + dtdSource + thirdPart;

      // Drop the comments; we don't need them.
      while (doctype.indexOf("<!--") != -1) {
        refIndex = doctype.indexOf("<!--");
        firstPart = doctype.substr(0, refIndex);
        refIndex = doctype.indexOf("-->", refIndex + 4);
        thirdPart = doctype.substr(refIndex + 3);
        doctype = firstPart + thirdPart;
      }

      // Clean out the old references.
      var entityList = this.getDTDExternalEntities(dtdWrapper);
      for (i = 0; i < entityList.length; i++) {
        while (doctype.indexOf("%" + entityList[i] + ";") != -1) {
          refIndex  = doctype.indexOf("%" + entityList[i] + ";");
          firstPart = doctype.substr(0, refIndex);
          thirdPart = doctype.substr(refIndex + entityList[i].length + 2);
          doctype = firstPart + thirdPart;
        }
      }

      // Replace the original doctype (for parsing only) with processed version.
      refIndex  = contents.indexOf(aWrapper.documentType);
      firstPart = contents.substr(0, refIndex);
      thirdPart = contents.substr(refIndex + aWrapper.documentType.length);
      contents  = firstPart + doctype + thirdPart;
    }

    // <?xml-stylesheet ?> handling
    const stylePI = "<?xml-stylesheet";
    refIndex = contents.indexOf(stylePI);
    const hrefRE = /href\s*=\s*(['"])([^\1]*)\1/m;
    if (refIndex != -1) {
      var styleContents = contents;
      do {
        // Extract the processing instruction and its href pseudo-attribute.
        var closeIndex = styleContents.indexOf("?>", refIndex + stylePI.length);
        var instruction = styleContents.substring(refIndex, closeIndex + 2);
        var href = instruction.match(hrefRE)[2];

        if (href.indexOf("virtual://") == 0) {
          refIndex = styleContents.indexOf("<?xml-stylesheet", refIndex + 1);
          continue;
        }

        const chromeRE = /^chrome:\/\/([^\/]*)\/([^\/]*)\//;
        var chromePath = href.match(chromeRE);
        if ((chromePath[1] == "global") ||
            (chromePath[1] == "toolkit")) {
          refIndex = styleContents.indexOf("<?xml-stylesheet", refIndex + 1);
          continue;
        }

        var localBase = aPack.getBaseURI(href).getPrimaryLocalURI(href);
        if (localBase.indexOf("jar:") == 0) {
          // XXX ajvincent We don't yet support jarred files.
          refIndex = styleContents.indexOf("<?xml-stylesheet", refIndex + 1);
          continue;
        }

        var styleWrapper = aPack.getWrapper(href);
        if (!styleWrapper) {
          refIndex = styleContents.indexOf("<?xml-stylesheet", refIndex + 1);
          continue;
        }

        // Splice virtual:// hyperlink reference into processing instruction.
        var virtualHref = virtualFS.convertURIToVirtual(href);
        firstPart = instruction.substr(0, instruction.indexOf(href));
        thirdPart = instruction.substr(instruction.indexOf(href) + href.length);
        instruction = firstPart + virtualHref + thirdPart;

        // Splice new stylesheet PI into contents.
        firstPart = styleContents.substr(0, refIndex);
        thirdPart = styleContents.substr(closeIndex + 2);
        styleContents = firstPart + instruction + thirdPart;

        refIndex = styleContents.indexOf("<?xml-stylesheet", refIndex + 1);
      } while (refIndex != -1);

      contents = styleContents;
    }

    // SAXReader sanity check
    XMLValidator.validate(contents);

    // Parse document
    this.contentDocument = parser.parseFromString(contents, "application/xml");
    this.contentDocument.normalize();
    virtualFS.setDocumentPack(null);

    // Node position service for entity reference identification
  },

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

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

  // nsIClassInfo
  classDescription: "Verbosio XML Document File",

  // nsIClassInfo
  classID: Components.ID("{353f1c91-fdc8-459d-b9a2-e1079b6a9c52}"),

  // nsIClassInfo
  contractID: "@verbosio.mozdev.org/document-file;1?contentType=application/xml",

  // nsIClassInfo
  implementationLanguage: nsIProgrammingLanguage.JAVASCRIPT,

  // nsIClassInfo
  flags: 0,

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

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

var NSGetModule = XPCOMUtils.generateNSGetModule([
  DocumentFile,
  XMLDocumentFile
], null, null);
