/*
All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/5.0/esri/copyright.txt for details.
*/
import{Evented as e}from"../../../core/Evented.js";import{findInMap as t,someMap as s}from"../../../core/MapUtils.js";import{GraphicsMap as i}from"./GraphicsMap.js";class n extends e{constructor(e){super(),this._limit=e,this._all=new i,this._active=new r(this),this._pending=new Map,this._handle=this._all.on("change",e=>this._handleChanges(e))}destroy(){super.destroy(),this._handle.remove()}get length(){return this._active.length}toArray(){return this._active.toArray()}find(e){return this._active.find(e)}some(e){return this._active.some(e)}forEach(e){this._active.forEach(e)}addMany(e){this._all.addMany(e)}removeManyByObjectId(e){this._all.removeManyByObjectId(e)}_handleChanges(e){let t=e.removed;if(this._pending.size>0){t=new Array;for(const s of e.removed)this._pending.delete(s.objectId)||t.push(s)}let s=this._limit-this._active.length+t.length;s<e.added.length&&(this._active.removeMany(t),t=[],a.reset(1-this._limit/(this._active.length+e.added.length)),this._active.forEach(e=>{a.sample()&&(t.push(e),this._pending.set(e.objectId,e))}),s=this._limit-this._active.length+t.length);let i=e.added;if(s<e.added.length){i=new Array,a.reset(s/e.added.length);for(const t of e.added)a.sample()?i.push(t):this._pending.set(t.objectId,t)}const n=s-i.length;n>0&&this._pending.size>0&&(a.reset(n/this._pending.size),this._pending.forEach(e=>{a.sample()&&(i.push(e),this._pending.delete(e.objectId))})),this._active.addAndRemove(i,t)}}class h{constructor(){this._percentage=1,this._last=-1,this._index=0}reset(e){this._percentage=e,this._last=-1}sample(){const e=Math.floor(this._index*this._percentage);return++this._index,e!==this._last&&(this._last=e,!0)}}const a=new h;class r{constructor(e){this._parent=e,this._map=new Map}get length(){return this._map.size}forEach(e){this._map.forEach(t=>e(t))}find(e){return t(this._map,e)}some(e){return s(this._map,e)}toArray(){return Array.from(this._map.values())}addAndRemove(e,t){for(const s of e)this._map.set(s.objectId,s);for(const s of t)this._map.delete(s.objectId);(e.length>0||t.length>0)&&this._parent.emit("change",{added:e,removed:t})}removeMany(e){for(const t of e)this._map.delete(t.objectId);e.length>0&&this._parent.emit("change",{added:[],removed:e})}}export{n as LimitGraphicsMap};
