import { Controller } from "@hotwired/stimulus"
import { get } from '@rails/request.js'

export default class extends Controller {
  
  static values = {    
    url: String
  }

  connect () {
    this.fetchingData = false   
  }

  appendAttachments(event) {
    
    if (this.fetchingData) return
    
    const checkedCheckboxes = this.element.querySelectorAll('input[name="asset_ids[]"]:checked')
    const checkedValues = Array.from(checkedCheckboxes).map(checkbox => checkbox.value)
    
    this.getAttachments(checkedValues)
    
    this.dispatch("click", { target: document.getElementById('overlay'), prefix: null})
    
  }

  async getAttachments(ids) {
    this.fetchingData = true   
    await get(this.urlValue, { query: {asset_ids: ids.join(',')}, responseKind: "turbo-stream" } )
    this.fetchingData = false
  }
  
  
}
