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

const DRAGULA_CONFIG = {
  options: {
    copy: false,
    revertOnSpill: false,
    removeOnSpill: false,
    // item list row components can only be dragged by the header
    moves(el, container, handle) {
      let grippers = container.getElementsByClassName('playlist-editor-card__gripper');
      return [].slice.call(grippers).reduce((acc,curr) => {return acc || curr.contains(handle);}, false);

    }
  },
  enabledEvents: ['drag', 'drop']
};

export default Component.extend({
  attributeBindings: ['testSelector:data-test-selector'],
  testSelector: null,
  openItemsModal() {},
  removeItemFromPlaylist() {},

  items: null,
  hasPlaylistItems: computed.notEmpty('items'),
  dragulaConfig: DRAGULA_CONFIG,
  itemSort: ['position'],
  orderedItems: computed.sort('items', 'itemSort'),
  currentItemIndex: -1,
  actions: {
    onDrag(el) {
      let index = [].slice.call(el.parentElement.children).indexOf(el);
      this.set('currentItemIndex', index);
    },
    onDrop(el) {
      const oldIndex = this.get('currentItemIndex');
      const item = this.get('orderedItems')[oldIndex];
      const newIndex = [].slice.call(el.parentElement.children).indexOf(el);
      if(newIndex - oldIndex > 0) {
        // We're dragging the first item ourself so ignore it, slice is exclusive so go one
        // item extra
        this.get('orderedItems').slice(oldIndex + 1, newIndex + 1).forEach((displacedItem) => {
          displacedItem.decrementProperty('position');
        });
      } else {
        this.get('orderedItems').slice(newIndex, oldIndex).forEach((displacedItem) => {
          displacedItem.incrementProperty('position');
        });
      }

      item.set('position', newIndex);
      item.save();
    }
  }
});
