export class MessageBus {
	constructor() {
		this.log = false
		this.bus = new EventTarget()
	}

	subscribe(eventName, fn) {
		if (this.log) {
			console.groupCollapsed('MBUS subscribe   - ', eventName);
			console.trace(); // hidden in collapsed group
			console.groupEnd();
		}

		this.bus.addEventListener(eventName, event=>{
			fn(event)
			if (event.detail.callback !== undefined)
				event.detail.callback(event)
		})
	}

	unsubscribe(eventName, fn) {
		if (this.log) {
			console.groupCollapsed('MBUS unsubscribe - ', eventName);
			console.trace(); // hidden in collapsed group
			console.groupEnd();
		}

		this.bus.removeEventListener(eventName, fn)
	}

	dispatch(eventName, data, callback) {
		if (this.log) {
			console.groupCollapsed('MBUS dispatch    - ', eventName);
			console.log('data', data);
			console.trace(); // hidden in collapsed group
			console.groupEnd();
		}

		const event = new CustomEvent(eventName, {
			detail: {
				data,
				callback,
			}
		})

		this.bus.dispatchEvent(event)
	}
}
