import { Controller } from '@hotwired/stimulus';

/* stimulusFetch: 'lazy' */
export default class extends Controller {
  static targets = ['icon']
  static values = {
    url: String
  }

  connect() {
    this.defaultIconClass = this.iconTarget.classList.value;
  }

  async download(event) {
    event.preventDefault();

    // Change the icon to a loader
    this.iconTarget.classList.remove("fa-download", "fa-search");
    this.iconTarget.classList.add("fa-spinner", "fa-spin");

    try {
      const response = await fetch(this.urlValue, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'X-Requested-With': 'XMLHttpRequest'
        }
      });

      const contentType = response.headers.get("Content-Type");
      if (contentType && contentType.includes("application/json")) {
        const data = await response.json();
        if (data.error) {
          this.dispatchAlert(data.error, 'error');
        } else if (data.success) {
          this.dispatchAlert(data.success, 'success');
        }
      } else {
        // C'est un fichier à télécharger
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        const contentDisposition = response.headers.get('Content-Disposition');
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(contentDisposition);
        let filename = 'download';
        if (matches != null && matches[1]) {
          filename = matches[1].replace(/['"]/g, '');
        }
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      }
    } finally {
      // Revert the icon back to the original one
      this.iconTarget.classList.value = this.defaultIconClass;
    }
  }

  dispatchAlert(message, level) {
    const event = new CustomEvent('alert:show', {
      detail: { message: message, level: level }
    });
    window.dispatchEvent(event);
  }
}
