import Component from 'ember-component';
import run from 'ember-runloop';

export default Component.extend({
  classNames: ['balloon-wrapper'],

  attributeBindings: [
    'testSelector:data-test-selector'
  ],

  isMenuOpen: false,
  isDropMenu: true,

  willDestroyElement() {
    this._super(...arguments);
    this._removeBodyClickListener();
  },

  actions: {
    close() {
      this._close();
    },

    toggle() {
      if (this.get('isMenuOpen')) {
        this._close();
      } else {
        this._open();
      }
    }
  },

  _close() {
    this.set('isMenuOpen', false);
    this._removeBodyClickListener();
  },

  _open() {
    this.set('isMenuOpen', true);
    this._setupBodyClickListener();
  },

  _removeBodyClickListener() {
    this.$(document.body).off(`click.${this.elementId}`);
  },

  _setupBodyClickListener() {
    this.$(document.body).on(`click.${this.elementId}`, event => {
      if (this.isDestroyed) { return; }
      if (this.$().has(event.target).length !== 0) { return; }

      run(this, this._close);
    });
  }
});
