1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Custom binding for the webstore API.
6
7var webstoreNatives = requireNative('webstore');
8
9function Installer() {
10  this._pendingInstall = null;
11}
12
13Installer.prototype.install = function(url, onSuccess, onFailure) {
14  if (this._pendingInstall)
15    throw 'A Chrome Web Store installation is already pending.';
16  var installId = webstoreNatives.Install(url, onSuccess, onFailure);
17  if (installId !== undefined) {
18    this._pendingInstall = {
19      installId: installId,
20      onSuccess: onSuccess,
21      onFailure: onFailure
22    };
23  }
24};
25
26Installer.prototype.onInstallResponse = function(installId, success, error) {
27  var pendingInstall = this._pendingInstall;
28  if (!pendingInstall || pendingInstall.installId != installId) {
29    // TODO(kalman): should this be an error?
30    return;
31  }
32
33  try {
34    if (success && pendingInstall.onSuccess)
35      pendingInstall.onSuccess();
36    else if (!success && pendingInstall.onFailure)
37      pendingInstall.onFailure(error);
38  } catch (e) {
39    console.error('Exception in chrome.webstore.install response handler: ' +
40                  e.stack);
41  } finally {
42    this._pendingInstall = null;
43  }
44};
45
46var installer = new Installer();
47
48var chromeWebstore = {
49  install: function install(url, onSuccess, onFailure) {
50    installer.install(url, onSuccess, onFailure);
51  }
52};
53
54// Called by webstore_binding.cc.
55function onInstallResponse(installId, success, error) {
56  installer.onInstallResponse(installId, success, error);
57}
58
59// These must match the names in InstallWebstorebinding in
60// chrome/renderer/extensions/dispatcher.cc.
61exports.chromeWebstore = chromeWebstore;
62exports.onInstallResponse = onInstallResponse;
63