App.FileUploadProgress = {
  // Creates a new progress bar element
  createProgressBar: id => {
    // <div class="progress">
    const progress = document.createElement("div")
    progress.setAttribute("id", `progress_bar_${id}`)
    progress.setAttribute("hidden", "hidden")
    progress.classList.add("mt-2")
    progress.classList.add("progress")

    // <div class="progress-bar">
    const progressBar = document.createElement("div")
    progressBar.setAttribute("role", "progressbar")
    progressBar.setAttribute("aria-valuenow", "0")
    progressBar.setAttribute("aria-valuemin", "0")
    progressBar.setAttribute("aria-valuemax", "100")
    progressBar.classList.add("progress-bar")

    progress.appendChild(progressBar)

    return progress
  },

  // Unhides an existing progress bar
  showProgressBar: id => {
    const progressBar = App.FileUploadProgress._findProgressBar(id)
    progressBar.removeAttribute("hidden")
    progressBar.firstChild.setAttribute("style", "width: 0%")
  },

  // Updates the progress of an existing progress bar
  updateProgressBar: (id, progress) => {
    const progressBar = App.FileUploadProgress._findProgressBar(id)
    progressBar.firstChild.setAttribute("style", `width: ${progress}%`)
    progressBar.firstChild.setAttribute("aria-valuenow", progress)
  },

  // Shows an error message
  showError: (id, error) => {
    // <div class="text-danger>...</div>
    const errorMsg = document.createElement("div")
    errorMsg.classList.add("text-danger")
    errorMsg.appendChild( document.createTextNode(error) )

    const progressBar = App.FileUploadProgress._findProgressBar(id)
    progressBar.parentNode.replaceChild(errorMsg, progressBar)
  },

  // Removes a progress bar element from the document
  removeProgressBar: id => {
    const progressBar = App.FileUploadProgress._findProgressBar(id)
    progressBar.parentNode.removeChild(progressBar)
  },

  // Finds a progress bar element by the given ID
  _findProgressBar: id => {
    return document.getElementById(`progress_bar_${id}`)
  }
}
