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

/* stimulusFetch: 'lazy' */
export default class extends Controller {
  static targets = ['progressBar', 'progressText']
  static values = {
    chapterId: Number
  }

  connect() {
    this.currentPage = 0;
    this.totalPages = 0;

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

    this.eventSource.onmessage = this.handleMessage.bind(this);
  }

  disconnect() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  }

  handleMessage(event) {
    const data = JSON.parse(event.data);
    if (data.status === "scrapping.progress" && data.chapterId === this.chapterIdValue) {
      this.handleProgressUpdate(data);
    }
  }

  handleProgressUpdate(data) {
    this.currentPage = data.pageIndex;
    this.totalPages = data.totalPages;

    this.updateProgressBar();
  }

  updateProgressBar() {
    const progress = (this.currentPage / this.totalPages) * 100;
    this.progressBarTarget.style.width = `${progress}%`;
    this.progressTextTarget.textContent = `${this.currentPage} / ${this.totalPages}`;
  }
}
