import { PeerSet } from "./set.js";
class TrackedPeerSet extends PeerSet {
    metric;
    constructor(init) {
        super();
        const { name, metrics } = init;
        this.metric = metrics.registerMetric(name);
        this.updateComponentMetric();
    }
    add(peer) {
        super.add(peer);
        this.updateComponentMetric();
    }
    delete(peer) {
        super.delete(peer);
        this.updateComponentMetric();
    }
    clear() {
        super.clear();
        this.updateComponentMetric();
    }
    updateComponentMetric() {
        this.metric.update(this.size);
    }
}
/**
 * Creates a PeerSet that reports it's size to the libp2p Metrics service
 *
 * @example Tracked peer sets
 *
 * ```Typescript
 * import { trackedPeerSet } from '@libp2p/peer-collections'
 * import { createLibp2p } from 'libp2p'
 *
 * const libp2p = await createLibp2p()
 *
 * const list = trackedPeerSet({ name: 'my_metric_name', metrics: libp2p.metrics })
 * map.add(peerId)
 * ```
 */
export function trackedPeerSet(config) {
    const { name, metrics } = config;
    let map;
    if (metrics != null) {
        map = new TrackedPeerSet({ name, metrics });
    }
    else {
        map = new PeerSet();
    }
    return map;
}
//# sourceMappingURL=tracked-set.js.map