import TurboStreamController from "@symfony/ux-turbo/dist/turbo_stream_controller";
import {connectStreamSource, disconnectStreamSource} from "@hotwired/turbo";

export default class extends TurboStreamController {

// We override the Stimulus TurboStream component to add withCredentials: true,
// allowing Firefox (among others) to connect to the Mercure hub with the authorization cookie.
// Without this, private push notifications cannot be sent on Firefox.
  connect() {
    const metaValue = document.querySelector('meta[name="x-mer"]')?.content;
    if (metaValue && !this.url.includes('&authorization=')) {
      this.url = this.url + '&authorization=' + metaValue;
    }
    this.es = new EventSource(this.url, {withCredentials: true});
    connectStreamSource(this.es);
  }
}
