/**
 * On form submit, add a new opener
 */
function form_create_opener (e) {
  // Do not submit HTML form
  e.preventDefault()

  // Get data and send to API
  const formData = new FormData(e.target)
  $.getJSON('/api/note/alias/'+formData.get('opener') + '/',
    function (opener_alias) {
      create_opener(formData.get('activity'), opener_alias.note)
    }).fail(function (xhr, _textStatus, _error) {
        errMsg(xhr.responseJSON)
    })
}

/**
 * Add an opener between an activity and a user
 * @param activity:Integer activity id
 * @param opener:Integer user note id
 */
function create_opener(activity, opener) {
  $.post('/api/activity/opener/', {
      activity: activity,
      opener: opener,
      csrfmiddlewaretoken: CSRF_TOKEN
  }).done(function () {
  // Reload tables
  $('#opener_table').load(location.pathname + ' #opener_table')
    addMsg(gettext('Opener successfully added'), 'success')
  }).fail(function (xhr, _textStatus, _error) {
    errMsg(xhr.responseJSON)
  })
}

/**
 * On click of "delete", delete the opener
 * @param button_id:Integer Opener id to remove
 */
function delete_button (button_id) {
  $.ajax({
    url: '/api/activity/opener/' + button_id + '/',
    method: 'DELETE',
    headers: { 'X-CSRFTOKEN': CSRF_TOKEN }
  }).done(function () {
    addMsg(gettext('Opener successfully deleted'), 'success')
    $('#opener_table').load(location.pathname + ' #opener_table')
  }).fail(function (xhr, _textStatus, _error) {
    errMsg(xhr.responseJSON)
  })
}

$(document).ready(function () {
  // Attach event
  document.getElementById('form_opener').addEventListener('submit', form_create_opener)
})
