import Ember from 'ember';
import IntervalTree from 'interval-tree';

export default Ember.Component.extend({

  classNames: ['transcript-component'],

  player: Ember.inject.service(),

  autoscrollElement: '.corpus-app-container',
  previousElement: 0,
  autoscroll: Ember.computed.alias('player.autoscroll'),
  timeout: null,

  transcript: Ember.computed.readOnly('player.transcript'),
  hasSections: Ember.computed('transcript', function () {
    var sections = this.get('transcript.sections');
    return sections && sections.length > 0;
  }),

  didReceiveAttrs() {
    this._super(...arguments);
  },

  itemObserver: Ember.observer('player.item', function () {
    if (!(this.get('isDestroyed') || this.get('isDestroying'))) {
      this.set('autoscroll', true);
    }
  }),

  didInsertElement() {
    Ember.$('#' + this.elementId).parent().on('scroll', Ember.run.bind(this, this.onScroll));
    var intervals = new IntervalTree(this.get('player.model.duration_ms') / 2);
    if (this.get('hasSections')) {
      this.get('transcript.sections').forEach((section, indexSection) => {
        section.turns.forEach((turn, indexTurn) => {
          let sentenceId = `#sentence-${indexSection}-${indexTurn}`;
          intervals.add(turn.begin, turn.end, sentenceId/*, this.$(sentenceId)*/);
        });
      });
    } else {
      this.get('transcript.annotations').forEach((annotation, index) => {
        let sentenceId = `#sentence-${index}`;
        intervals.add(annotation.begin, annotation.end, sentenceId/*, this.$(sentenceId)*/);
      });
    }
    this.set('intervals', intervals);
    this.get('player').set('transcriptLoading', false);
  },

  onScroll() {
    if (!(this.get('isDestroyed') || this.get('isDestroying'))) {
      this.set('autoscroll', false);
    }
    if (this.elementId) {
      Ember.$('#' + this.elementId).parent().off('scroll');
    }
  },

  scroll: Ember.observer('player.progress', function () {
    var self = this;
    var progress = this.get('player.progress');
    var previousElement = this.get('previousElement');
    if (previousElement && progress >= previousElement.start && progress < previousElement.end) {
      return;
    }
    var intervals = this.get('intervals');
    if (!intervals) {
      return;
    }
    var intervalList = intervals.search(progress);
    if (intervalList.length === 0) {
      return;
    }

    let previousDomElement = this.$('.sentence.active');

    if (previousDomElement) {
      previousDomElement.removeClass('active');
      Ember.$(".fa-play", previousDomElement).show();
    }

    var target = null;
    intervalList.forEach(interval => {
      let obj = this.$(interval.id);
      obj.addClass('active');
      Ember.$(".fa-play", obj).hide();
      if (!target) {
        target = interval;
        target.object = obj;
      }
    });

    if (this.get('autoscroll') && target.object.length && (!previousElement || target.id !== previousElement.id)) {
      Ember.$('#' + self.elementId).parent().off('scroll');
      Ember.$(this.get('autoscrollElement')).animate({
        scrollTop: target.object.offset().top + Ember.$(this.get('autoscrollElement')).scrollTop() - Ember.$(this.get('autoscrollElement')).offset().top - 154
      }, 150, 'swing', function () {
        setTimeout(function () {
          Ember.$('#' + self.elementId).parent().on('scroll', Ember.run.bind(self, self.onScroll));
        }, 100);
      });
      this.set('previousElement', target);
    }
  }),


  actions: {

    play: function (progress) {
      if(!!progress || progress === 0) {
        this.get('player').trigger('progressupdate', progress);
        this.get('player').set('playing', true);
      }
    }
  }

});
