/* COPYRIGHT Esri - https://js.arcgis.com/5.1.2/LICENSE.txt */
import{Evented as e}from"../../../../core/Evented.js";import"../../../../core/has.js";import{findInMap as t,someMap as s}from"../../../../core/MapUtils.js";class i extends e{constructor(e,t,s){super(),this._updateAndCompare=e,this._notifyUpdated=t,this._logError=s,this._nodes=new Map,this._graphics=new Map,this._duplicates=new Map}clear(){if(this._graphics.size>0){const e=this.toArray();this._graphics.clear(),this.emit("change",{added:[],removed:e})}this._nodes.clear()}get length(){return this._graphics.size}get(e){return this._graphics.get(e)}getNode(e){return this._nodes.get(e)}hasNode(e){return this._nodes.has(e)}nodes(){return this._nodes.values()}addNode(e,t){if(this._nodes.has(e))return void this._logError(`Added node[${e}] already added`);this._nodes.set(e,t);const s=t.graphics;if(0===s.length)return;const i=new Set;for(let o=0;o<s.length;o++){const t=s[o],n=t.objectId,r=this._graphics.get(n);if(r){i.add(n),t!==r&&(s[o]=r);const h=this._duplicates.get(n);h?h.push(e):this._duplicates.set(n,[r.nodeIndex,e])}else t.nodeIndex=e,this._graphics.set(n,t)}i.size&&this._updateForeignGraphics(t);const n=i.size>0?s.filter(e=>!i.has(e.objectId)):s;n.length>0&&this.emit("change",{added:n,removed:[]})}removeNode(e){const t=this._nodes.get(e);if(!t)return;this._nodes.delete(e);const s=new Set,i=[];for(const n of t.graphics){const t=n.objectId,o=this._graphics.get(t);if(!o)continue;const r=this._duplicates.get(t);if(r){const i=r.indexOf(e);if(-1===i)continue;if(r.splice(i,1),o.nodeIndex===e){let e=this.getNode(r[0]);for(let t=1;t<r.length;t++){const s=this.getNode(r[t]);(null==e||null!=s&&s.node.level>e.node.level)&&(e=s)}null!=e&&s.add(e)}1===r.length&&this._duplicates.delete(t)}else this._graphics.delete(t),i.push(n)}i.length>0&&this.emit("change",{added:[],removed:i}),s.forEach(e=>this._updateForeignGraphics(e))}_updateForeignGraphics(e){const t=[],s=e.node.index,i=e.node.level;let n=0;for(;n<e.graphics.length;){const o=e.graphics[n].nodeIndex;if(o===s){n++;continue}let r=1;for(;n+r<e.graphics.length&&e.graphics[n+r].nodeIndex===o;)r++;const h=this.getNode(o);if(null!=h&&h.node.level>i)n+=r;else{for(let i=n;i<n+r;i++){const n=e.graphics[i];n.nodeIndex=s,this._updateAndCompare(n,e,i)&&t.push(n)}n+=r}}t.length>0&&this._notifyUpdated(t)}toArray(){return Array.from(this._graphics.values())}find(e){return t(this._graphics,e)}some(e){return s(this._graphics,e)}forEach(e){this._graphics.forEach(t=>e(t))}forEachNode(e){this._nodes.forEach((t,s)=>e(t,s))}get nodeCount(){return this._nodes.size}_checkInvariants(){const e=new Map;this._nodes.forEach((t,s)=>{t.graphics.forEach(t=>{e.set(t.objectId,1+(e.get(t.objectId)??0)),this._duplicates.get(t.objectId)})}),e.forEach((e,t)=>{const s=this._graphics.get(t);if(!s)return;if(!this._nodes.get(s.nodeIndex))return;const i=this._duplicates.get(t);i&&i.forEach(e=>{this._nodes.get(e)})})}}export{i as I3SGraphicsMap};
