define([
  'core/js/adapt'
], function(Adapt) {

  var TrickleNotifyHandler = Backbone.Controller.extend({

    isStepLocking: false,
    isNotifyOpen: false,

    initialize: function() {
      this.listenToOnce(Adapt, "app:dataReady", this.onAppDataReady);
    },

    onAppDataReady: function() {
      this.setupEventListeners();
    },

    setupEventListeners: function() {
      this.listenTo(Adapt, {
        "trickle:steplock": this.onStepLock,
        "notify:opened": this.onNotifyOpened,
        "notify:closed": this.onNotifyClosed,
        "trickle:stepunlock": this.onStepUnlock,
        "remove": this.onRemove
      });
    },

    onStepLock: function(view) {
      this.isStepLocking = true;
    },

    onNotifyOpened: function() {
      if (!this.isStepLocking) return;

      this.isNotifyOpen = true;
      Adapt.trigger("trickle:overlay");
      Adapt.trigger("trickle:wait");
    },

    onNotifyClosed: function() {
      if (!this.isStepLocking) return;
      if (!this.isNotifyOpen) return;

      this.isNotifyOpen = false;
      Adapt.trigger("trickle:unoverlay");
      Adapt.trigger("trickle:unwait");
    },

    onStepUnlock: function() {
      this.isStepLocking = false;
    },

    onRemove: function() {
      this.onStepUnlock();
    }

  });

  return new TrickleNotifyHandler();

});
