import sortable from "sortablejs";
import clonedeep from "lodash.clonedeep";

const tableDrag = {
  bind(el, binding) {
    const { value, arg } = binding;
    if (!el) {
      return;
    }
    const { elementSeletor, onEnd, ...config } = arg || {};
    const bindEls = elementSeletor ? el.querySelector(elementSeletor) : el;
    el.sortable = sortable.create(bindEls, {
      animation: 150,
      ghostClass: "blue-background-class",
      ...config,
      handle: ".handle",
      onEnd: (evt) => {
        let cloneValue = null;
        if (Array.isArray(value)) {
          const { oldIndex, newIndex } = evt;
          cloneValue = clonedeep(value);
          value.splice(newIndex, 0, ...value.splice(oldIndex, 1));
        }

        onEnd && onEnd(evt, cloneValue, value);
      },
      onMove(e) {
        return e.related.className.indexOf("filtered") === -1;
      }
    });
    el.tableData = value;
  },

  update(el, { value }) {
    el.tableData = value;
  },

  unbind: function (el) {
    el.sortable.destroy();
    el.sortable = null;
  }
};

export default tableDrag;
