/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import{__decorate as e}from"tslib";import s from"../Accessor.js";import{makeHandle as t}from"../handleUtils.js";import{watch as i,when as n,on as d,sync as a}from"../reactiveUtils.js";import{schedule as r}from"../scheduling.js";import{property as o}from"../accessorSupport/decorators/property.js";import{subclass as l}from"../accessorSupport/decorators/subclass.js";let h=class extends s{constructor(){super(...arguments),this.updating=!1,this._handleId=0,this._scheduleHandleId=0,this._pendingPromises=new Set}destroy(){this.removeAll()}add(e,s,t={}){return this._installWatch(e,s,t,i)}addWhen(e,s,t={}){return this._installWatch(e,s,t,n)}addOnCollectionChange(e,s,{initial:i=!1,final:n=!1}={}){const r=++this._handleId;return this.addHandles([d(e,"after-changes",this._createSyncUpdatingCallback(),a),d(e,"change",s,{onListenerAdd:i?e=>s({added:e.toArray(),removed:[]}):void 0,onListenerRemove:n?e=>s({added:[],removed:e.toArray()}):void 0})],r),t(()=>this.removeHandles(r))}addPromise(e){if(null==e)return e;const s=++this._handleId;this.addHandles(t(()=>{this._pendingPromises.delete(e)&&(0!==this._pendingPromises.size||this.hasHandles(c)||this._set("updating",!1))}),s),this._pendingPromises.add(e),this._set("updating",!0);const i=()=>this.removeHandles(s);return e.then(i,i),e}removeAll(){this._pendingPromises.clear(),this.removeAllHandles(),this._set("updating",!1)}_installWatch(e,s,i={},n){const d=++this._handleId;i.sync||this._installSyncUpdatingWatch(e,d);const a=n(e,s,i);return this.addHandles(a,d),t(()=>this.removeHandles(d))}_installSyncUpdatingWatch(e,s){const t=this._createSyncUpdatingCallback(),n=i(e,t,{sync:!0,equals:()=>!1});return this.addHandles(n,s),n}_createSyncUpdatingCallback(){return()=>{this.removeHandles(c),++this._scheduleHandleId;const e=this._scheduleHandleId;this._get("updating")||this._set("updating",!0),this.addHandles(r(()=>{e===this._scheduleHandleId&&(this._set("updating",this._pendingPromises.size>0),this.removeHandles(c))}),c)}}};e([o({readOnly:!0})],h.prototype,"updating",void 0),h=e([l("esri.core.support.UpdatingHandles")],h);const c=-42;export{h as UpdatingHandles};
