import Component from 'ember-component';
import computed from 'ember-computed';
import config from 'web-client/config/environment';
import run from 'ember-runloop';
import $ from 'jquery';
import { htmlSafe } from 'ember-string';

const ANIMATE_OUT_TIME = config.fastAnimations ? 0 : 300;

export default Component.extend({
  init() {
    this._super(...arguments);
    this.pendingClose = undefined;
    this.isShowing = false;
    this._previousIsOpen = false;
  },

  didInsertElement() {
    this._super(...arguments);

    this.clickOutsideListener = (e) => {
      if (!$.contains(this.element, e.target)) {
        run(() => {
          this.get('onClickOutside')(e);
        });
      }
    };

    // Using `addEventListener` in order to hook into capture phase
    document.body.addEventListener('click', this.clickOutsideListener, true);
  },

  willDestroyElement() {
    document.body.removeEventListener('click', this.clickOutsideListener, true);
    run.cancel(this.pendingClose);
    this._super(...arguments);
  },

  didReceiveAttrs() {
    this._super(...arguments);
    let isOpen = Boolean(this.get('isOpen'));

    // Only continue if the isOpen property has changed
    if (this._previousIsOpen === isOpen) {
      return;
    }

    this._previousIsOpen = isOpen;

    if (isOpen) {
      this.set('isShowing', true);
      this.get('onOpen')();
      run.cancel(this.pendingClose);
      run.next(() => this.openSearchPanel());
    } else {
      this.closeSearchPanel();
      this.get('onClose')();
      this.pendingClose = run.debounce(this, this.immediatelyDestroyPanel, ANIMATE_OUT_TIME);
    }
  },

  openSearchPanel() {
    let panel = this.$('#search-panel');
    if (panel) {
      panel.removeClass('search-panel--closed');
    }
  },

  closeSearchPanel() {
    let panel = this.$('#search-panel');
    if (panel) {
      panel.addClass('search-panel--closed');
    }
  },

  immediatelyDestroyPanel() {
    this.set('isShowing', false);
  },

  style: computed('leftPosition', function() {
    if (this.get('leftPosition')) {
      return htmlSafe(`left: ${this.get('leftPosition')}px`);
    }
  })
});
