function beforeUnloadHandler(e){
  e.preventDefault();
  e.returnValue = '';
}

function turbolinksClickHandler(){
  return false;
}

let eventListenersAdded = false;

function addEventListenersForUploadProgresBar(){
  if (eventListenersAdded) return;
  eventListenersAdded = true;
  addEventListener("direct-upload:initialize", event => {
    const { detail } = event;
    const { id, file } = detail;
    const progressBar = App.FileUploadProgress.createProgressBar(id);

    $('#upload-progress-container').append(progressBar);
  });

  addEventListener("direct-upload:start", event => {
    const { id } = event.detail;
    App.FileUploadProgress.showProgressBar(id);
  })

  addEventListener("direct-upload:progress", event => {
    const { id, progress } = event.detail;
    if (App.FileUploadProgress._findProgressBar(id)) {
      App.FileUploadProgress.updateProgressBar(id, progress);
    }
  })

  addEventListener("direct-upload:error", event => {
    event.preventDefault();
    const { id, error } = event.detail;
    App.FileUploadProgress.showError(id, error);
  })

  addEventListener("direct-upload:end", event => {
    const { id } = event.detail;
    App.FileUploadProgress.removeProgressBar(id)
  })
}

$(document).on("turbolinks:load", function() {
  addEventListenersForUploadProgresBar();
  window.removeEventListener('beforeunload', beforeUnloadHandler, true);
  $(document).off('turbolinks:click', turbolinksClickHandler);

  $("#import_appearance_releases").click(function(e) {
    $('#appearance_release_file_upload').click();
  });

  $('#appearance_release_file_upload').change(function(e) {
    $('#import_appearance_releases')
      .html('Importing...')
      .attr('disabled', 'disabled');

    window.addEventListener('beforeunload', beforeUnloadHandler, true);
    $(document).on('turbolinks:click', turbolinksClickHandler);

    const fileUploadForm = document.getElementById('appearance_releases_import');
    Rails.fire(fileUploadForm, 'submit');
  });
});
