/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu, Constructor: CC } = Components;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/osfile.jsm");
Cu.import("resource://gre/modules/Promise.jsm");

this.EXPORTED_SYMBOLS = ["WebappOSUtils"];

// Returns the MD5 hash of a string.
function computeHash(aString) {
  let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
                  createInstance(Ci.nsIScriptableUnicodeConverter);
  converter.charset = "UTF-8";
  let result = {};
  // Data is an array of bytes.
  let data = converter.convertToByteArray(aString, result);

  let hasher = Cc["@mozilla.org/security/hash;1"].
               createInstance(Ci.nsICryptoHash);
  hasher.init(hasher.MD5);
  hasher.update(data, data.length);
  // We're passing false to get the binary hash and not base64.
  let hash = hasher.finish(false);

  function toHexString(charCode) {
    return ("0" + charCode.toString(16)).slice(-2);
  }

  // Convert the binary hash data to a hex string.
  return [toHexString(hash.charCodeAt(i)) for (i in hash)].join("");
}

this.WebappOSUtils = {
  getUniqueName: function(aApp) {
    return this.sanitizeStringForFilename(aApp.name).toLowerCase() + "-" +
           computeHash(aApp.manifestURL);
  },

//@line 75 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"

  /**
   * Returns the executable of the given app, identifying it by its unique name,
   * which is in either the new format or the old format.
   * On Mac OS X, it returns the identifier of the app.
   *
   * The new format ensures a readable and unique name for an app by combining
   * its name with a hash of its manifest URL.  The old format uses its origin,
   * which is only unique until we support multiple apps per origin.
   */
  getLaunchTarget: function(aApp) {
//@line 117 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
    let uniqueName = this.getUniqueName(aApp);

    let mwaUtils = Cc["@mozilla.org/widget/mac-web-app-utils;1"].
                   createInstance(Ci.nsIMacWebAppUtils);

    try {
      let path;
      if (path = mwaUtils.pathForAppWithIdentifier(uniqueName)) {
        return [ uniqueName, path ];
      }
    } catch(ex) {}

    // Fall back to the old installation naming scheme
    try {
      let path;
      if ((path = mwaUtils.pathForAppWithIdentifier(aApp.origin)) &&
           this.isOldInstallPathValid(aApp, path)) {
        return [ aApp.origin, path ];
      }
    } catch(ex) {}

    return [ null, null ];
//@line 166 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
  },

  getInstallPath: function(aApp) {
//@line 222 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
    // Anything unsupported, like Metro
    throw new Error("Unsupported apps platform");
  },

  getPackagePath: function(aApp) {
    let packagePath = this.getInstallPath(aApp);

    // Only for Firefox on Mac OS X
//@line 232 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
    packagePath = OS.Path.join(packagePath, "Contents", "Resources");
//@line 235 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"

    return packagePath;
  },

  launch: function(aApp) {
    let uniqueName = this.getUniqueName(aApp);

//@line 260 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
    let [ launchIdentifier, path ] = this.getLaunchTarget(aApp);
    if (!launchIdentifier) {
      return false;
    }

    let mwaUtils = Cc["@mozilla.org/widget/mac-web-app-utils;1"].
                   createInstance(Ci.nsIMacWebAppUtils);

    try {
      mwaUtils.launchAppWithIdentifier(launchIdentifier);
    } catch(e) {
      return false;
    }

    return true;
//@line 293 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
  },

  uninstall: function(aApp) {
//@line 331 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
    let [ , path ] = this.getLaunchTarget(aApp);
    if (!path) {
      return Promise.reject("App not found");
    }

    let deferred = Promise.defer();

    let mwaUtils = Cc["@mozilla.org/widget/mac-web-app-utils;1"].
                   createInstance(Ci.nsIMacWebAppUtils);

    mwaUtils.trashApp(path, (aResult) => {
      if (aResult == Cr.NS_OK) {
        deferred.resolve(true);
      } else {
        deferred.resolve("Error moving the app to the Trash: " + aResult);
      }
    });

    return deferred.promise;
//@line 376 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
  },

  /**
   * Returns true if the given install path (in the old naming scheme) actually
   * belongs to the given application.
   */
  isOldInstallPathValid: function(aApp, aInstallPath) {
    // Applications with an origin that starts with "app" are packaged apps and
    // packaged apps have never been installed using the old naming scheme.
    // After bug 910465, we'll have a better way to check if an app is
    // packaged.
    if (aApp.origin.startsWith("app")) {
      return false;
    }

    // Bug 915480: We could check the app name from the manifest to
    // better verify the installation path.
    return true;
  },

  /**
   * Checks if the given app is locally installed.
   */
  isLaunchable: function(aApp) {
    let uniqueName = this.getUniqueName(aApp);

//@line 409 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
    if (!this.getInstallPath(aApp)) {
      return false;
    }

    return true;
//@line 460 "/Users/t_mrc-ct/Projects/Tenfourbird/repos/comm-beta/mozilla/toolkit/webapps/WebappOSUtils.jsm"
  },

  /**
   * Sanitize the filename (accepts only a-z, 0-9, - and _)
   */
  sanitizeStringForFilename: function(aPossiblyBadFilenameString) {
    return aPossiblyBadFilenameString.replace(/[^a-z0-9_\-]/gi, "");
  }
}
