import { Controller } from "@hotwired/stimulus"
import TomSelect from "tom-select";

export default class extends Controller {

  connect() {
    this.initializeTomSelect();  
  }
  
  // Triggered when the Stimulus controller is removed from the DOM.
  disconnect() {
    this.destroyTomSelect();
  }
  

  // Initialize the TomSelect dropdown with the desired configurations.
  initializeTomSelect() {
    // Return early if no element is associated with the controller.
    if (!this.element) return;    
    
    this.select = new TomSelect(this.element, {
      create: this.element.getAttribute('data-tags') == 'true'
    });
  }

  destroyTomSelect() {
    if (this.select) {
      this.select.destroy();
    }
  }
}
