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 = ['activity']

  // ...
  async connect() {
    try {
      const response = await fetch(`/activity/status`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest'
        }
      });

      const data = await response.json();
      // Handle the response data as needed
      this.activityTarget.innerHTML = data.length;
      if (data.length > 0) {
        this.activityTarget.classList.remove('hidden');
      }
    } catch (error) {
      console.error('Error:', error);
    }


    const mercureHubUrl = 'https://mangarr.test.nestor-server.fr/.well-known/mercure';
    const eventSource = new EventSource(`${mercureHubUrl}?topic=activity`, {withCredentials: true});

    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.processing !== undefined && data.pending !== undefined) {
        let totalActivities = data.processing.length + data.pending.length;
        this.activityTarget.innerHTML = totalActivities;
        if (totalActivities > 0) {
          this.activityTarget.classList.remove('hidden');
        }else if (totalActivities === 0) {
          this.activityTarget.classList.add('hidden');
        }
      }
    };

    eventSource
      .onerror = (event) => {
      console.error('EventSource failed:', event);
    };
  }
}
