(function() {
  var jsm = { };
  Components.utils["import"]("resource://livemargins/utils.jsm", jsm);
  Components.utils["import"]("resource://livemargins/intent.jsm", jsm);
  Components.utils['import']('resource://livemargins/appcenter.jsm', jsm);

  function _getAppUID() {
    return widget.args.id;
  }

  let playerBrowser = document.getElementById("player_browser");
  playerBrowser.addEventListener("DOMContentLoaded", function(evt) {
    if (!(evt.originalTarget instanceof HTMLDocument)) {
      return;
    }

    var view = evt.originalTarget.defaultView;
    if (!view || view.top != view) {
      return;
    }

    var unsafeWindow = view.window.wrappedJSObject;

    if (!unsafeWindow.navigator.apps) {
      unsafeWindow.navigator.apps = jsm.utils.exposeReadOnly({
        services: {
          registerHandler: function(action, handler) {
            if (_getAppUID() != action) {
              throw new Error("Action id does not match.");
            }
            jsm.AppIntent.registerHandler(action, handler);
          },

          unregisterHandler: function(action, handler) {
            if (_getAppUID() != action) {
              throw new Error("Action id does not match.");
            }
            jsm.AppIntent.unregisterHandler(action, handler);
          }
        },

        updateAppInfo: function(appInfo) {
          if (!appInfo || !appInfo.appUID) {
            return;
          }

          // Only could be invoked from allowed sites.
          var strDomains = jsm.utils.getPref('appsites');
          var domains = strDomains.split(/\d*,\d*/);
          for (var i = 0; i < domains.length; i++) {
            let hostname = view.document.location.hostname;
            if (jsm.utils.isChildDomain(hostname, domains[i])) {
              AppCenter.updateApp(appInfo);
              break;
            }
          }
        }
      });
    }
  }, false);
})();

