import { Injectable } from '@angular/core';
import { Subject, Subscription } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EventService {
  private channels: Map<string, Subject<any>> = new Map();

  publish(eventName: string, data?: any): void {
    if (!this.channels.has(eventName)) {
      this.channels.set(eventName, new Subject<any>());
    }
    this.channels.get(eventName)!.next(data);
  }

  subscribe(eventName: string, callback: (data: any) => void): Subscription {
    if (!this.channels.has(eventName)) {
      this.channels.set(eventName, new Subject<any>());
    }
    return this.channels.get(eventName)!.subscribe(callback);
  }

  unsubscribe(eventName: string): void {
    if (this.channels.has(eventName)) {
      this.channels.get(eventName)!.complete();
      this.channels.delete(eventName);
    }
  }
}
