const t=require("compact-encoding"),e=require("protomux");function n(){}module.exports=class{constructor({onupdate:t=n,validate:e=null}={}){this._own=null,this._changes=0,this._onupdate=t,this._validate=e,this._links=new Map}get sharing(){return null!==this._own}get changes(){return this._changes}get peers(){let t=0;for(const e of this._links.values())e.remote&&t++;return t}contactInfos(){const t=[];for(const{remote:e}of this._links.values())e&&t.push(e);return t}setContactInfo(t,e=""){this._share({contactInfo:t,avatar:e||""})}clearContactInfo(){this._share(null)}_share(t){const e=null!==t&&null===this._own;if(this._own=t,!t)for(const t of this._links.values())t.remote=null;for(const t of this._links.keys())this._send(t,e);this._changed()}attach(n){const s=e.from(n).createChannel({protocol:"keet/nearby/v1",onopen:()=>this._send(s),onclose:()=>this._detach(s),ondestroy:()=>this._detach(s),messages:[{encoding:t.json,onmessage:t=>this._onremote(s,t)}]});s&&(this._links.set(s,{message:s.messages[0],remote:null}),s.open())}clear(){this._own=null,this._links.clear()}_send(t,e=!1){const n=this._links.get(t);if(!n)return;const s=this._own||{contactInfo:""};n.message.send(e?{...s,resend:!0}:s)}_onremote(t,e){const n=this._links.get(t);if(!n)return;const s="string"==typeof e?.contactInfo?e.contactInfo:"",o="string"==typeof e?.avatar?e.avatar:"";if(s.length>4096||o.length>65536)return void t.close();if(!0===e?.resend&&this.sharing&&this._send(t),!this.sharing)return;const a=s&&(null===this._validate||this._validate(s))?{contactInfo:s,avatar:o}:null;!!a==!!n.remote&&(!a||a.contactInfo===n.remote.contactInfo&&a.avatar===n.remote.avatar)||(n.remote=a,this._changed())}_detach(t){const e=this._links.get(t);this._links.delete(t),e?.remote&&this._changed()}_changed(){this._changes++,this._onupdate()}};