/* COPYRIGHT Esri - https://js.arcgis.com/5.1.2/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 d,on as n,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,d)}addOnCollectionChange(e,s,{initial:i=!1,final:d=!1}={}){const r=++this._handleId;return this.addHandles([n(e,"after-changes",this._createSyncUpdatingCallback(),a),n(e,"change",s,{onListenerAdd:i?e=>s({added:e.toArray(),removed:[]}):void 0,onListenerRemove:d?e=>s({added:[],removed:e.toArray()}):void 0})],r),t(()=>this.removeHandles(r))}consumePromise(e){this.addPromise(e)?.catch(()=>{})}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={},d){const n=++this._handleId;i.sync||this._installSyncUpdatingWatch(e,n);const a=d(e,s,i);return this.addHandles(a,n),t(()=>this.removeHandles(n))}_installSyncUpdatingWatch(e,s){const t=this._createSyncUpdatingCallback(),d=i(e,t,{sync:!0,equals:()=>!1});return this.addHandles(d,s),d}_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};
