/* ***** 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 Pack Service, JavaScript.
 *
 * The Initial Developer of the Original Code is
 * Alexander J. Vincent <ajvincent@gmail.com>.
 * Portions created by the Initial Developer are Copyright (C) 2005-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 ***** */

// Component metadata.  Please change all the values in this section.

var componentName     = "Language Checker Service, JavaScript";
var contractId = "@verbosio.mozdev.org/language-pack-service;1?contentType=application/javascript";
var componentId = Components.ID("{460e4931-eb4f-43a4-ad01-8c7a09e27161}");

// 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 xeISourceMapCreator         = C_i.xeISourceMapCreator;
const xeISourceMap                = C_i.xeISourceMap;
const xeILanguagePackService      = C_i.xeILanguagePackService;
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;

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

// Language pack service constructor.
function languagePack()
{
  loadDebugging();
}
languagePack.prototype = {
  // xeISourceMapCreator
  createSourceMap: function createSourceMap() {
    var mapContractId = "@verbosio.mozdev.org/source-map;1?contentType=";
    mapContractId += this.contentType;
    var sourceMap = Components.classes[mapContractId]
                              .createInstance(xeISourceMap);
    return sourceMap;
  },

  // xeILanguagePackService
  contentType: "application/javascript",

  // xeILanguagePackService
  specificationURI: "http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference",

  // xeILanguagePackService
  description: "JavaScript",

  // xeILanguagePackService
  id: "JavaScript",

  // xeILanguagePackService
  version: "1.7",

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

  // xeILanguagePackService
  getFirstSyntaxError: function getFirstSyntaxError(wrapper) {
    try {
      var sandboxURL = "http://verbosio.mozdev.org/sandbox?date=" + (new Date()) * 1
      sandboxURL += "&salt=" + String(Math.random()).substr(2);
      const sandbox = new Components.utils.Sandbox(sandboxURL);
    }
    catch (e) {
      if (e.name == "SyntaxError") {
        var scriptError = Components.classes("@mozilla.org/scripterror;1")
                                    .createInstance(nsIScriptError);
        var lineNumber = e.lineNumber;
        var sourceLine = wrapper.wrappedSource.split("\n")[lineNumber - 1];

        scriptError.init(e.message,
                         wrapper.publicURI,
                         sourceLine,
                         e.lineNumber,
                         0,
                         nsIScriptError.errorFlag);
        return scriptError;
      }
    }
    return null;
  },

  // nsIClassInfo
  getInterfaces: function getInterfaces(aCount) {
    var interfaces = [xeILanguagePackService,
                      xeISourceMapCreator,
                      nsIClassInfo];
    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(xeILanguagePackService) ||
        aIID.equals(xeISourceMapCreator) ||
        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: " + prop + "\n");
        break;
      }
    }
    if (!found) {
      dump("QUERYINTERFACE: 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;
}
