class Event {

    constructor(name) {
        this.name = name
        this.firings = []
        this.subscriptions = []
    }

    subscribe(handler) {
        if ( typeof handler !== 'function' ) {
            throw new TypeError('Event subscription handlers must be functions.')
        }

        this.subscriptions.push(handler)
    }

    async fire(...args) {
        this.firings.push({ args })

        return Promise.all(this.subscriptions.map(x => x(...args)))
    }
}

class EventBusService {
    constructor() {
        this._events = {}
    }

    event(name) {
        if ( !this._events[name] ) {
            this._events[name] = new Event(name)
        }

        return this._events[name]
    }
}

const event_bus = new EventBusService()
export { event_bus, Event }
