const e=require("hypercore-id-encoding"),t=require("ready-resource"),a=require("ble-swarm"),s=require("./nearby"),{hash:n}=require("hypercore-crypto"),r=require("safety-catch"),i=n(require("b4a").from("keet-ble"));module.exports=class extends t{constructor(e,t={}){super(),this.keet=e,this.enabled=!1,this.swarm=new a({...t,keyPair:e.swarm.keyPair,topic:i,tag:"keet-ble-v1",online:!1!==e.swarm.dht.online}),this.nearby=new s({onupdate:()=>this.emit("update"),validate:e=>this._readableContactInfo(e)}),this._onNetworkUpdate=()=>this.swarm.setOnline(!1!==this.keet.swarm.dht.online),this.keet.swarm.dht.on("network-update",this._onNetworkUpdate),this.swarm.on("connection",e=>{this.keet._handleConnection(e),this.nearby.attach(e)}),this.swarm.on("update",()=>this.emit("update"))}get state(){return this.swarm.state}get isEnabled(){return!0===this.enabled}status(){const t=[];for(const a of this.swarm.connections)a.remotePublicKey&&t.push(e.encode(a.remotePublicKey));return{state:this.state,enabled:this.enabled,peers:t.length,peerIds:t,id:this.keet.swarmId,nearby:{sharing:this.nearby.sharing,changes:this.nearby.changes}}}async setEnabled(e){this.enabled=!0===e,this.enabled?await this.swarm.start():await this.swarm.stop(),this.emit("update")}_readableContactInfo(e){try{return this.keet.internalDecodeContactInfo(e),!0}catch{return!1}}async setNearbyContactInfo(e,t){this.keet.internalDecodeContactInfo(e),this.nearby.setContactInfo(e,t),this.emit("update")}async clearNearbyContactInfo(){this.nearby.clearContactInfo(),this.emit("update")}async suspend(){await this.swarm.suspend()}async resume(){await this.swarm.resume()}async _close(){this.nearby.clear(),this.keet.swarm.dht.off("network-update",this._onNetworkUpdate),await this.swarm.close().catch(r)}};