/* COPYRIGHT Esri - https://js.arcgis.com/5.1.2/LICENSE.txt */
import{BufferView as e}from"./bufferview.js";class i{constructor(e){this._gltf=e,this._bufferViews=[],this._isFinalized=!1,e.buffers||(e.buffers=[]),this.index=e.buffers.length;const i={byteLength:-1};e.buffers.push(i),this._buffer=i}addBufferView(i,t,r){if(this._finalizePromise)throw new Error("Cannot add buffer view after fiinalizing buffer");const f=new e(this,this._gltf,i,t,r);return this._bufferViews.push(f),f}getByteOffset(e){let i=0;for(const t of this._bufferViews){if(t===e)return i;i+=t.byteSize}throw new Error("Given bufferView was not present in this buffer")}getViewFinalizePromises(e){const i=[];for(const t of this._bufferViews){if(e&&t===e)return i;i.push(t.finalized)}return i}getArrayBuffer(){if(!this._isFinalized)throw new Error("Cannot get ArrayBuffer from Buffer before it is finalized");const e=this._getTotalSize(),i=new ArrayBuffer(e);let t=0;for(const r of this._bufferViews)r.writeOutToBuffer(i,t),t+=r.byteSize;return i}finalize(){if(this._finalizePromise)throw new Error(`Buffer ${this.index} was already finalized`);return this._finalizePromise=Promise.allSettled(this.getViewFinalizePromises()).then(()=>{this._isFinalized=!0;const e=this.getArrayBuffer();this._buffer.byteLength=e.byteLength,this._buffer.uri=e}),this._gltf.extras.promises.push(this._finalizePromise),this._finalizePromise}_getTotalSize(){let e=0;for(const i of this._bufferViews)e+=i.byteSize;return e}}export{i as Buffer};
