import Ember from 'ember';

/**
 * Mixin to detect outside click for a component.
 * taken from http://stackoverflow.com/a/32115231
 */
export default Ember.Mixin.create({
  onOutsideClick: Ember.K,
  onOutsideClickEnabled: true,

  handleOutsideClick: function(event) {
    var element = this.$();
    var target = Ember.$(event.target);
    if(element && target) {
      if (!(element.has(target).length || element.is(target))) {
        this.onOutsideClick();
      }
    }
  },

  _registerOutsideClickListener() {
    let clickHandler = this.get('handleOutsideClick').bind(this);

    return Ember.$(document).on('click', clickHandler);
  },

  _unregisterOutsideClickListener() {
    let clickHandler = this.get('handleOutsideClick').bind(this);

    return Ember.$(document).off('click', clickHandler);
  },

  _onOutsideClickEnabledChanged: Ember.observer('onOutsideClickEnabled', function() {
    if(this.get('onOutsideClickEnabled')) {
      this._registerOutsideClickListener();
    }
    else {
      this._unregisterOutsideClickListener();
    }
  }),

  setupOutsideClickListener: Ember.on('didInsertElement', function() {
    this._super(...arguments);
    if(this.get('onOutsideClickEnabled')) {
      return this._registerOutsideClickListener();
    }
    else {
      return Ember.$(document);
    }
  }),

  removeOutsideClickListener: Ember.on('willDestroyElement', function() {
    return this._unregisterOutsideClickListener();
  })
});
