import { BaseService } from './abstract/baseService';

class EventEmitter extends BaseService {
    public static sharedInstance = new EventEmitter();
    protected logTag: string = 'EventEmitter';

    public broadcastEvent<T>(eventName: string, data: T | null = null, dispatcher: HTMLElement = document.body) {
        let event;
        if (typeof (window as any).CustomEvent === 'function' || (window as any).CustomEvent.toString().indexOf('CustomEventConstructor') > -1) {
            event = new CustomEvent(eventName, { detail: data });
        } else {
            event = document.createEvent('CustomEvent') as CustomEvent;
        }
        event.initCustomEvent(eventName, true, true, data);
        dispatcher.dispatchEvent(event);
    }

    public on<T>(eventName: string, callback: (eventDetail: T) => void) {
        document.addEventListener(eventName, (domEvent: CustomEvent<T>) => {
            this.logInfo(`Received event ${eventName}`);
            callback(domEvent.detail);
        });
    }
}

export default EventEmitter.sharedInstance as EventEmitter;