/* globals i18n */

import Component from 'ember-component';
import Ember from 'ember';

const { $, Handlebars } = Ember;
const { escapeExpression } = Handlebars.Utils;

const SCROLL_SPEED = 200;

export default Component.extend({
  tagName: "div",
  classNames: ['draggable-item'],

  _initDraggable: function () {
    let draggableOptions = {
      start: function (event, ui) {
        $(this).addClass('dragging');

        let scrollContainer = $('.playlist-container .tse-scroll-content');
        let containerHeight = scrollContainer.outerHeight();
        let contentBottom = $('.playlist-container .tse-content').outerHeight() - containerHeight;

        if (scrollContainer.scrollTop() === contentBottom) {
          // display last item guide
          $('.js-playlist-drag-guide').show();

          scrollContainer.stop().animate({
            'scrollTop': contentBottom + $('.js-playlist-drag-guide').outerHeight(true)
          }, SCROLL_SPEED, 'linear');
        }

        // clean clone
        $(ui.helper)
          .removeClass('item')
          .find('.title span').unwrap();
        $(ui.helper).find(".description, .actions").remove();

        // display warning message when playlist is active
        let sortableContainer = $(".draggable-dropzone .zone-container");
        let message = i18n('You can’t edit your playlist while it’s broadcasting');

        if (sortableContainer.sortable("option", "disabled")) {
          $(ui.helper).toggleClass('drag-message');
          $(ui.helper).prepend(`<p class="helper-message">${escapeExpression(message)}</p>`);
        }
      },
      stop: function () {
        $(this).removeClass('dragging');
        $('.js-playlist-drag-guide').hide();

        if ($('.playlist li').length > 0) {
          $('.intro').hide();
        }
      },
      appendTo: $('.app-main'),
      cursorAt: {top: 45, left: 180},
      connectToSortable: ".draggable-dropzone .zone-container"
    };

    $('.video.item').draggable(draggableOptions, {
      helper: 'clone'
    });
  },

  didInsertElement: function () {
    this._initDraggable();
  }
});
