import { PeerList } from "./list.js";
class TrackedPeerList extends PeerList {
    metric;
    constructor(init) {
        super();
        const { name, metrics } = init;
        this.metric = metrics.registerMetric(name);
        this.updateComponentMetric();
    }
    pop() {
        const peerId = super.pop();
        this.updateComponentMetric();
        return peerId;
    }
    push(...peerIds) {
        super.push(...peerIds);
        this.updateComponentMetric();
    }
    shift() {
        const peerId = super.shift();
        this.updateComponentMetric();
        return peerId;
    }
    unshift(...peerIds) {
        const result = super.unshift(...peerIds);
        this.updateComponentMetric();
        return result;
    }
    clear() {
        super.clear();
        this.updateComponentMetric();
    }
    updateComponentMetric() {
        this.metric.update(this.length);
    }
}
/**
 * Creates a PeerList that reports it's size to the libp2p Metrics service
 *
 * @example
 *
 * ```Typescript
 * import { trackedPeerList } from '@libp2p/peer-collections'
 * import { createLibp2p } from 'libp2p'
 *
 * const libp2p = await createLibp2p()
 *
 * const list = trackedPeerList({ name: 'my_metric_name', metrics: libp2p.metrics })
 * list.push(peerId)
 * ```
 */
export function trackedPeerList(config) {
    const { name, metrics } = config;
    let map;
    if (metrics != null) {
        map = new TrackedPeerList({ name, metrics });
    }
    else {
        map = new PeerList();
    }
    return map;
}
//# sourceMappingURL=tracked-list.js.map