<script>
  function builder_remove(index, deck) {
      htmx.ajax('POST', '/builder/remove?index=' + index + '&deck=' + deck, {
          target:'#current-deck-list',
          values:{"_csrf_token":"{{ csrf_token }}"}
      });
  }

  function builder_add(passcode, deck) {
      htmx.ajax('POST', '/builder/add/' + passcode + '?deck=' + deck, {
          target:'#current-deck-list',
          values:{"_csrf_token":"{{ csrf_token }}"}
      });
  }

  $(function() {
      $(".droppable").droppable({
          accept: ".draggable",
          drop: function( event, ui ) {
              var draggable = ui.draggable.clone();
              var droppable = $(this).clone();
              /* It came from the search results */
              if (draggable.find('td').length > 0) {
                  /* TODO Fix this monstrosity and use data-passcode in the future! */
                  var maybe_passcode = draggable.find('td').find('a').attr('id').split('-')[1];
                  var maybe_deck = droppable.attr('id').split('-')[0];
                  builder_add(maybe_passcode, maybe_deck);
              }
              /* You probably dragged it from one deck area to another */
              else {
                  const data_class = draggable.data('class');
                  const data_index = draggable.data('index');
                  const data_passcode = draggable.data('passcode');
                  const data_deck = droppable.attr('id').split('-')[0];
                  console.log(data_index, data_class, data_passcode, data_deck);
                  if (data_class != data_deck) {
                      builder_remove(data_index, data_class);
                      builder_add(data_passcode, data_deck);
                  }
              }
              draggable.remove();
              droppable.remove();
          }
      });
      $(".draggable").draggable({
          appendTo: "body",
          helper: "clone",
          stack: ".draggable"
      });
  });
</script>
