<%
  buttons = @easy_page_modules_data[block_name][:buttons]
%>

<div id="<%= modul_uniq_id %>_errors" class="easy-button-drop-zone-errors">
</div>

<div id="<%= modul_uniq_id %>" class="">
  <% buttons.each do |button| %>
    <a class="easy-button-drop-zone fc-event <%= button.color %>" href="#" data-css-to-entity="fc-event <%= button.color %>" data-url="<%= execute_easy_button_path(button, format: 'js') %>">
      <span class="name"><%= button.name %></span>

      <ul></ul>
    </a>
  <% end %>
</div>

<script>
  $("#<%= modul_uniq_id %> .easy-button-drop-zone").droppable({
    hoverClass: "hover",
    accept: function(item) {
      return '<%= settings['button_type'] %>' == item.parent().data().entityType;
    },
    drop: function(event, ui) {
      // Issue, CRMCase, ...
      var entity = ui.draggable.parent();

      // Current dropzone
      var dropZone = $(this);

      // Execute entity on dropzone
      $.ajax({
        url: dropZone.data().url,
        data: { entity_id: entity.data().entityId, api: true },
        dataType: 'text',
        success: function(data){
          // Got new ajax
          var response = eval(data);

          // Sometimes there is parseerror on 200 OK
          response.always(function(response){
            var errorContainer = $("#<%= modul_uniq_id %>_errors");
            errorContainer.html('');

            switch(response.status){
              // OK
              case 200:
                  // Set css to entity row
                  entity.parents("tr").addClass(dropZone.data().cssToEntity);

                  // Append to list - changed entity
                  $("ul", dropZone).append("<li>" + entity.text() + "</li>");

                  break;

              // Forbidden
              case 403:
                  errorContainer.html(response.statusText);
                  errorContainer.effect("highlight", "slow");
                  break;

              // Unprocessable Entity
              case 422:
                  errorContainer.html(response.responseJSON.errors.join('<br>'));
                  errorContainer.effect("highlight", "slow");
                  break;
            }

          })
        }
      });
    }
  });
</script>


<% content_for :header_tags do %>
  <%= stylesheet_link_tag 'easy_buttons',  plugin: 'easy_buttons' %>
<% end %>
