/* globals _ */
import run from 'ember-runloop';
import Mixin from 'ember-metal/mixin';

export default Mixin.create({

  _loadingIndicatorRequested: false,

  /*
   * loadingOptions = {
   *   isLoadingProperty: property name to check to determine if data is loading
   *   hideMoreProperty: property name to check to determine whether to hide Load More
   *   onlyIfProperty: additional property name to check to determine whether to load
   *   buttonSelector: selector for Load More button
   *   sectionSelector: selector for content
   * }
   */
  initLoading(loadingOptions) {
    loadingOptions = _.defaults(loadingOptions || {}, {
      isLoadingProperty: 'isLoading',
      hideMoreProperty: 'hideMore'
    });

    let _setLoadingIndicator = () => {
      this._loadingIndicatorRequested = true;
      run.schedule('afterRender', () => {
        if (this.isDestroyed || this.isDestroying || !this._loadingIndicatorRequested) {
          return;
        }
        this._loadingIndicatorRequested = false;

        if (loadingOptions.onlyIfProperty) {
          if (!this.get(loadingOptions.onlyIfProperty)) {
            return;
          }
        }
        if (loadingOptions.buttonSelector) {
          let button = this.$(loadingOptions.buttonSelector);

          let opts = {
            lines: 12,
            length: 3,
            width: 2,
            radius: 6
          };

          if (button) {
            if (this.get(loadingOptions.isLoadingProperty)) {
              button.show().spin(opts).addClass('invis');
            } else {
              button.spin(false).removeClass('invis');
              if (this.get(loadingOptions.hideMoreProperty)) {
                button.hide();
              }
            }
          }
        } else if (loadingOptions.sectionSelector) {
          let sectionLoad = this.$(loadingOptions.sectionSelector);
          if (sectionLoad) {
            if (this.get(loadingOptions.isLoadingProperty)) {
              sectionLoad.spin().removeClass('hidden');
            } else {
              sectionLoad.spin(false).addClass('hidden');
            }
          }
        }
      });
    };

    _setLoadingIndicator();
    this.addObserver(loadingOptions.isLoadingProperty, _setLoadingIndicator);
    this.addObserver('application.currentPath', _setLoadingIndicator);
  }

});
