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

export default class extends Controller {
  connect() {
    this.sortable = new Sortable(this.element, {
      onEnd: this.end.bind(this),
      handle: '.handle'
    })    
    
  }

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

  end(event) {
    
    // sortableUrl
    if (this.element.dataset.sortableUrl != undefined) {
      const item = this.element.children[event.newIndex]
      const url = this.element.dataset.sortableUrl        
      const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

      const formData = new FormData()
      formData.append('id', item.dataset.id)
      formData.append('new_index', event.newIndex)
      // console.log("Move", event.oldIndex, "to", event.newIndex);

      fetch(url, {
        method: 'PATCH',
        headers: {
          'Accept': "text/vnd.turbo-stream.html",
          'X-CSRF-Token': token
        },
        body: formData            
      })
      .then (response => response.text())
      .then(html => Turbo.renderStreamMessage(html))
      .catch((err) => {
        console.info('rejected', err)
      })
    } else {
      this.element.querySelectorAll('input.position').forEach((input, index) => {
        input.value = index + 1  
      })
    }
  }


}
