class Admin.ReorderableTable
  constructor: (selector) ->
    $(selector).find("ul").sortable
      items:  "li"
      handle: ".js-reorder-handle" # from `reorderable_column` above
      update: @_sendPositions

  _calculatePositions: (sortable) ->
    # Sortable uses ids by default for serialisation
    for itemId, index in $(sortable).sortable("toArray")
      # ActiveAdmin sets the id to the form "underscored_classname_id"
      id:    itemId.split("_").pop()
      order: index + 1

  _sendPositions: (event) =>
    positions = items: @_calculatePositions(event.target)

    # `url` assumes that we're on the index page, with no extra params
    $.ajax
      url:         $(this).data("url")
      method:      "PATCH"
      dataType:    "json"
      contentType: "application/json"
      data:        JSON.stringify(positions)


# Initialise on page load
$ ->
  new Admin.ReorderableTable(".project_partials")