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

/*
* The following line makes this controller "lazy": it won't be downloaded until needed
* See https://github.com/symfony/stimulus-bridge#lazy-controllers
*/
/* stimulusFetch: 'lazy' */
export default class extends Controller {
    // ...
  static targets = ["textarea", "submitButton"]

  connect() {
    document.addEventListener('openImportModal', this.prepareImportModal.bind(this));
    document.addEventListener('openExportModal', this.prepareExportModal.bind(this));
  }

  disconnect() {
    document.removeEventListener('openImportModal', this.prepareImportModal.bind(this));
    document.removeEventListener('openExportModal', this.prepareExportModal.bind(this));
  }

  async prepareExportModal() {
    try {
      const response = await fetch('/settings/export_scrappers');
      const data = await response.json();
      this.textareaTarget.value = JSON.stringify(data, null, 2);
      this.submitButtonTarget.textContent = 'Copy to Clipboard';
      this.submitButtonTarget.dataset.action = 'scrapper-import#copyToClipboard';
      this.openModal('Export Scrapper Configurations');
    } catch (error) {
      console.error('Error:', error);
    }
  }

  prepareImportModal() {
    this.textareaTarget.value = '';
    this.submitButtonTarget.textContent = 'Import';
    this.submitButtonTarget.dataset.action = 'scrapper-import#submitImport';
    this.openModal('Import Scrapper Configurations');
  }

  openModal(title) {
    const event = new CustomEvent('openScrapperModal', { detail: { title: title } });
    document.dispatchEvent(event);
  }

  async submitImport() {
    const jsonData = this.textareaTarget.value;

    try {
      const response = await fetch('/settings/import_scrappers', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonData
      });

      const result = await response.json();

      if (response.ok) {
        console.log(result.message);
        document.dispatchEvent(new CustomEvent('closeScrapperModal'));
        window.location.reload();
      } else {
        console.error(result.error);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  }

  copyToClipboard() {
    navigator.clipboard.writeText(this.textareaTarget.value).then(() => {
      console.log('Copied to clipboard');
      document.dispatchEvent(new CustomEvent('closeScrapperModal'));
    }, (err) => {
      console.error('Could not copy text: ', err);
    });
  }
}
