class EventManager {
    constructor() {
        this.listeners = {};
    }

    addListener(event, handler) {
        const id = Math.floor(Math.random()*1e12).toString(36);

        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }

        this.listeners[event].push({ handler, id });

        return {
            remove: () => {
                for (let i = this.listeners[event].length - 1; i >= 0; i--) {
                    if (this.listeners[event][i].id === id) {
                        this.listeners[event].splice(i, 1);
                    }
                }
            }
        };
    }

    dispatchEvent(event) {
        if (!this.listeners[event]) {
            return;
        }

        for (let i = 0, n = this.listeners[event].length; i < n; i++) {
            this.listeners[event][i].handler();
        }
    }
}

export default EventManager;
