import Component from 'ember-component';
import run from 'ember-runloop';
import injectService from 'ember-service/inject';
import $ from 'jquery';

export default Component.extend({
  tagName: '',
  layout: injectService(),

  didInsertElement() {
    this._initScroller();
    this._initTooltips();

    // this defers the update until after the initial render
    // which allows the measurement to succeed and avoid deprecations
    // when we change properties that are bound into the DOM
    // this is not something that should commonly be needed
    run.scheduleOnce('afterRender', this, this._attachWindowResizeHandler);

    // Wait until Ember rendered the title once, then remove the title provided by Rails
    run.scheduleOnce('afterRender', this, this._removeRailsTitle);
  },

  willDestroyElement() {
    this._boxartTipsySelector.teardownTipsy();
    if ($('#main_col.scroll').data('plugin_TrackpadScrollEmulator')) {
      $('#main_col.scroll').TrackpadScrollEmulator('destroy');
    }
    this._super(...arguments);
  },

  _initScroller() {
    this.runTask(() => {
      $('#main_col.scroll').TrackpadScrollEmulator({
        wrapContent: false,
        scrollbarHideStrategy: 'rightAndBottom'
      });
    });
  },

  _initTooltips() {
    this._boxartTipsySelector = $('.video .boxart, .card__boxpin, .stream .boxart, .user .image').tipsy({
      gravity: 'n',
      live: true
    });
  },

  _setWindowSize() {
    let layoutService = this.get('layout');
    let win = $(window);
    let winWidth = win.width();
    let winHeight = win.height();

    layoutService.set('windowWidth', winWidth);
    layoutService.set('windowHeight', winHeight);
    layoutService.set('isRightColumnClosedByWindowResize', winWidth < 920);
    layoutService.set('isLeftColumnClosedByWindowResize', winWidth < 1200);
  },

  _attachWindowResizeHandler: function () {
    this._setWindowSize();
    this.addEventListener(window, 'resize', () => {
      this.debounceTask('_setWindowSize', 50);
    });
  },

  _removeRailsTitle: function () {
    let $titles = $('head title');
    if ($titles.length > 1) {
      $titles.filter(':first').remove();
    }
  }

});
