/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import{toPartialCoords as t,Part as e,addVertexAndConnectingSegment as i}from"../EditGeometry.js";class s{constructor(t,e,i,s){this._editGeometry=t,this._positions=e,this._part=i,this._viewingMode=s,this._addedPart=null,this._originalPositions=null,this._hasApplied=!1}get part(){return this._addedPart}apply(){const s=this._editGeometry,r=s.parts,o=this._part;if(!this._hasApplied&&o&&r.includes(o)){const e=o.getFirstVertex(),i=o.getLastVertex();this._originalPositions=t(s,{startingVertex:e,endingVertexInclusive:i}).parts[0]}const n=this._addedPart??this._part??(this._addedPart=new e(s.spatialReference,this._viewingMode,"polygon"===s.type));r.includes(n)||(r.push(n),n.index=r.length-1);const a=n.vertices.slice(),d=[];n.segments.length=0,n.vertices.length=0;let p=null;for(const t of this._positions)p=i(n,s.coordinateHelper,p,t),d.push(p);this._hasApplied=!0,s.notifyChanges({operation:this._hasApplied?"redo":"apply",addedVertices:d,removedVertices:a,addedParts:this._addedPart?[this._addedPart]:void 0})}undo(){if(!this._hasApplied)return;const{_editGeometry:t,_addedPart:e}=this;if(e){const i=t.parts.indexOf(e);if(-1!==i)return t.parts.splice(i,1),void t.notifyChanges({operation:"undo",removedVertices:e.vertices.slice(),removedParts:[e]})}const s=this._part;if(!s||!t.parts.includes(s)||!this._originalPositions)return;const r=Array.from(s.iterateVertices()),o=[];s.vertices.length=0,s.segments.length=0;let n=null;for(const a of this._positions)n=i(s,t.coordinateHelper,n,a),o.push(n);t.notifyChanges({operation:"undo",addedVertices:o,removedVertices:r})}accumulate(t){return t instanceof s&&null!=t._part&&(t._part===this._addedPart||t._part===this._part)&&(this._positions=t._positions,this.apply(),!0)}}export{s as AddOrUpdatePart};
