const e = require("hypercore-id-encoding")
module.exports = class {
constructor(i, { call: t, prev: n, deviceKey: o, debug: h }) {
;((this.call = t),
(this.isOldEngine = 1 === t?.version || 1 === n?.version),
(this.connections = this.isOldEngine ? new s(i, n, h) : null),
(this.deviceId = o ? e.encode(o) : null))
}
get joined() {
return this.connections ? this.connections.joined : new Set()
}
get callId() {
return this.call ? this.call.callId : null
}
get version() {
return this.call ? this.call.version : 0
}
get ended() {
return !this.call || !this.deviceId
}
_close() {
this.connections && this.connections.close()
}
refresh() {
if (this.connections) {
if (this.ended) return this._close()
for (const e of this.call.members)
for (const s of e.devices) this.connections.shouldJoin(s.swarmId)
this.connections.refresh()
}
}
}
class s {
constructor(e, s, i) {
;((this.swarm = e),
(this.debug = i),
(this._prevJoined = s ? s.joined : new Set()),
(this.joined = new Set(this._prevJoined)),
(this._shouldJoin = new Set()),
(this._shouldLeave = new Set(this._prevJoined)))
}
get swarmId() {
return e.encode(this.swarmKey)
}
get swarmKey() {
return this.swarm.keyPair.publicKey
}
shouldJoin(e) {
e !== this.swarmId && (this._shouldJoin.add(e), this._shouldLeave.delete(e))
}
refresh() {
;(this._joinPeers(), this._leavePeers())
}
close() {
this._leavePeers()
}
_joinPeers() {
for (const s of this._shouldJoin)
this._prevJoined.has(s) ||
(this.swarm.joinPeer(e.decode(s)),
this.joined.add(s),
this.debug.joinPeer && this.debug.joinPeer(s))
this._shouldJoin = new Set()
}
_leavePeers() {
for (const s of this._shouldLeave)
(this.swarm.leavePeer(e.decode(s)),
this.joined.delete(s),
this.debug.leavePeer && this.debug.leavePeer(s))
this._shouldLeave = new Set()
}
}