import { onCleanup, onMount } from "solid-js";
import Sortable from "sortablejs";

// https://github.com/SortableJS/Sortable

export const sortable = (el: HTMLElement, config: () => Sortable.Options) => {
  onMount(function () {
    const config_ = config();

    const userOnEnd = config_?.onEnd;
    if (userOnEnd) {
      config_.onEnd = (evt) => {
        // Undoes the dom structure of the list after a drag event. Ultimately this is needed to gain compatibility between sortablejs and solidjs
        if (evt.oldIndex != null && evt.newIndex != null) {
          const parent = evt.from;
          const oldNextSibling =
            parent.children[
              evt.oldIndex + (evt.oldIndex > evt.newIndex ? 1 : 0)
            ];
          if (oldNextSibling) {
            parent.insertBefore(evt.item, oldNextSibling);
          } else {
            parent.append(evt.item);
          }
        }

        userOnEnd(evt);
      };
    }

    const sortable = Sortable.create(el, config_);

    onCleanup(function () {
      sortable.destroy();
    });
  });
};

declare module "solid-js" {
  namespace JSX {
    interface Directives {
      sortable: Sortable.Options;
    }
  }
}

/*
let sortableDiv: HTMLDivElement = undefined;
onMount(function () {
  const sortable = Sortable.create(sortableDiv, {
    dragClass: "sortable-drag-card",
    ghostClass: "sortable-ghost-card",
    filter: ".drag-disabled",
    forceFallback: true,
    onEnd: (evt) => {
      const parent = evt.from;
      const oldNextSibling =
        parent.children[evt.oldIndex + (evt.oldIndex > evt.newIndex ? 1 : 0)];
      if (oldNextSibling) {
        parent.insertBefore(evt.item, oldNextSibling);
      } else {
        parent.append(evt.item);
      }

      setPositions(
        produce((positions: any[]) => {
          let item = positions[evt.oldIndex];
          positions.splice(evt.oldIndex, 1);
          positions.splice(evt.newIndex, 0, unwrap(item));
        })
      );
    },
  });

  onCleanup(function () {
    sortable.destroy();
  });
});
*/
