import*as Workspace from"../workspace/workspace.js";export class ChunkedFileReader{constructor(e,i,r){this._file=e,this._fileSize=e.size,this._loadedSize=0,this._chunkSize=i,this._chunkTransferredCallback=r,this._decoder=new TextDecoder,this._isCanceled=!1,this._error=null}read(e){return this._chunkTransferredCallback&&this._chunkTransferredCallback(this),this._output=e,this._reader=new FileReader,this._reader.onload=this._onChunkLoaded.bind(this),this._reader.onerror=this._onError.bind(this),this._loadChunk(),new Promise((e=>{this._transferFinished=e}))}cancel(){this._isCanceled=!0}loadedSize(){return this._loadedSize}fileSize(){return this._fileSize}fileName(){return this._file?this._file.name:""}error(){return this._error}_onChunkLoaded(e){if(this._isCanceled)return;if(e.target.readyState!==FileReader.DONE)return;if(!this._output||!this._reader)return;const i=this._reader.result;this._loadedSize+=i.byteLength;const r=this._loadedSize===this._fileSize,t=this._decoder.decode(i,{stream:!r});if(this._output.write(t),!this._isCanceled){if(this._chunkTransferredCallback&&this._chunkTransferredCallback(this),r)return this._file=null,this._reader=null,this._output.close(),void this._transferFinished(!this._error);this._loadChunk()}}_loadChunk(){if(!this._output||!this._reader||!this._file)return;const e=this._loadedSize,i=Math.min(this._fileSize,e+this._chunkSize),r=this._file.slice(e,i);this._reader.readAsArrayBuffer(r)}_onError(e){const i=e.target;this._error=i.error,this._transferFinished(!1)}}export class FileOutputStream{constructor(){this._writeCallbacks=[]}async open(e){this._closed=!1,this._writeCallbacks=[],this._fileName=e;const i=await Workspace.FileManager.FileManager.instance().save(this._fileName,"",!0);return i&&Workspace.FileManager.FileManager.instance().addEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this),Boolean(i)}write(e){return new Promise((i=>{this._writeCallbacks.push(i),Workspace.FileManager.FileManager.instance().append(this._fileName,e)}))}async close(){this._closed=!0,this._writeCallbacks.length||(Workspace.FileManager.FileManager.instance().removeEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this),Workspace.FileManager.FileManager.instance().close(this._fileName))}_onAppendDone(e){if(e.data!==this._fileName)return;const i=this._writeCallbacks.shift();i&&i(),this._writeCallbacks.length||this._closed&&(Workspace.FileManager.FileManager.instance().removeEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this),Workspace.FileManager.FileManager.instance().close(this._fileName))}}