"use strict";

import { Controller } from "@hotwired/stimulus";
import Sortable from "sortablejs";

export default class extends Controller {
  connect() {
    this.sortable = Sortable.create(this.element, {
      onEnd: this.onEnd.bind(this),
      animation: 150,
      ghostClass: "opacity-25",
      handle: ".drag-handle",
      dataIdAttr: "data-uuid",
    });
  }

  onEnd() {
    const uuids = this.sortable.toArray();

    this.element.dispatchEvent(
      new CustomEvent("live:action", {
        detail: {
          action: "reorderAttachments",
          params: { uuids },
        },
        bubbles: true,
      })
    );
  }

  disconnect() {
    this.sortable.destroy();
  }
}
