import Ember from 'ember';

export default Ember.Component.extend({
  constants: Ember.inject.service(),

  classNames: ['autoscroll-component'],
  tagName: "span",
  attributeBindings: ['title'],

  title: Ember.computed.readOnly('text'),

  text: null,
  textWidth: null,
  doScroll: false,
  keyFrameStyleDef: null,
  scrollRate: null,

  willDestroyElement() {
    const keyFrameStyleDef = this.get('keyFrameStyleDef');
    if(keyFrameStyleDef !== null) {
        Ember.run(() => {
          Ember.$(keyFrameStyleDef).remove();
        });
        this.set('keyFrameStyleDef', null);
    }
  },

  didRender() {
    const textWidth = this.$('span').width();
    if(textWidth === this.get('textWidth')) {
      return;
    }
    this.set('textWidth', textWidth);
    const outerWidth = this.$().width();
    const doScroll = (textWidth > outerWidth);
    const id = this.elementId;

    Ember.run(() => {
      if(this.get('keyFrameStyleDef') !== null) {
        Ember.$(this.get('keyFrameStyleDef')).remove();
      }
      if(doScroll) {
        const scrollRate = this.get('scrollRate') || this.get('constants').AUTOSCROLL_RATE;
        const duration = Math.ceil((textWidth + 30) / scrollRate) + 1;
        const firstFramePercent = Math.ceil((1/duration)*100);

        var keyframesDef = '';
        ['-webkit-', '-moz-', ''].forEach(function(p) {
          keyframesDef += `@${p}keyframes marquee-${id} { 0% { left: 0; } ${firstFramePercent}% { left: 0; } 100% { left: -${textWidth + 30 }px; } }\n`;
        });
        this.set(
          'keyFrameStyleDef',
          Ember.$("<style>")
            .prop('id', 'scroll-style-'+id)
            .prop("type", "text/css")
            .text(keyframesDef)
            .appendTo("head")
        );
        this.$('div').css('animation', `marquee-${id} ${duration}s linear infinite`);
        this.$('span:last-child').removeClass('hidden-double');
      } else {
        this.$('span:last-child').addClass('hidden-double');
        this.$('div').css('animation', '');
      }
    });

  }
});
