import Component from 'ember-component';
import computed from 'ember-computed';
import observer from 'ember-metal/observer';
import injectService from 'ember-service/inject';
import run from 'ember-runloop';

export default Component.extend({
  layout: injectService(),
  classNames: ['product__description', 'read-more'],
  actions: {
    toggle() {
      this.toggleProperty('isOpen');
      this._contentHeight();
    }
  },

  didInsertElement() {
    this._super(...arguments);
    run.scheduleOnce('afterRender', this, '_setReadMoreButton');
    this.get('layout.contentWidth'); // trigger the layout observer
  },

  resizeObserver: observer('layout.contentWidth', function() {
    this.debounceTask('_setReadMoreButton', 100);
  }),

  _setReadMoreButton() {
    let containerEl = this.$('.read-more-content');
    let contentEl = this.$('.product__description-content');
    this.set('contentHeight', contentEl[0].scrollHeight);

    let maxHeight = this.get('maxHeight');
    let contentHeight = this.get('contentHeight');

    if (contentHeight < maxHeight) {
      this.$('.read-more-button').addClass('hide');
      containerEl.height(contentHeight);
    } else {
      this.$('.read-more-button').removeClass('hide');
      containerEl.height(maxHeight);
    }
    this.set('isOpen', false);
  },
  
  isOpen: false,
  contentHeight: 0,
  maxHeight: 0,
  toggleClass: 'read-more-toggle',
  openText: 'Read more', // TODO Localize these strings
  closeText: 'Read less', // TODO Localize these strings

  toggleText: computed('openText', 'closeText', 'isOpen', function() {
    return this.get('isOpen') ? this.get('closeText') : this.get('openText');
  }),

  _contentHeight() {
    let containerEl = this.$('.read-more-content');

    if (this.get('isOpen')) {
      containerEl.animate({height: this.get('contentHeight')}, 100, 'linear');
    } else {
      containerEl.animate({height: this.get('maxHeight')}, 100, 'linear');
    }
  }
});
