/* COPYRIGHT Esri - https://js.arcgis.com/5.1.2/LICENSE.txt */
import{remove as t}from"../arrayUtils.js";import e from"../Handles.js";import{makeHandle as s}from"../handleUtils.js";import i from"../Logger.js";import{removeMaybe as r}from"../maybe.js";import{throwIfAborted as n,createAbortError as o}from"../promiseUtils.js";import{open as h}from"../workers.js";class a{constructor(t,e,s,r,n={}){this._mainMethod=e,this._transferLists=s,this._listeners=[],this._onClientConnectedHandle=null,this._destroyed=!1,this._promise=h(t,{...n,schedule:r}).then(t=>{null!=this._thread||this._destroyed?t.close():(this._thread=t,this._promise=null,this._onClientConnectedHandle=this._thread.onClientConnected(t=>{n.hasInitialize&&t.invoke("initialize",{});for(const e of this._listeners)this._connectListenerToClient(e,t);this._onClientConnected(t)}))}),this._promise.catch(e=>i.getLogger("esri.core.workers.WorkerHandle").error(`Failed to initialize ${t} worker: ${e}`))}on(e,i){const r=new d(e,i);return this._listeners.push(r),this._connectListener(r),s(()=>{t(this._listeners,r),r.destroy()})}[Symbol.dispose](){this.destroy()}destroy(){this._onClientConnectedHandle=r(this._onClientConnectedHandle),this._thread&&(this._thread.close(),this._thread=null),this._promise=null;for(const t of this._listeners)t.destroy();this._listeners.length=0,this._transferLists={},this._destroyed=!0}invoke(t,e,s){return this.invokeMethod(this._mainMethod,t,e,s)}invokeMethod(t,e,s,i){if(this._thread){const r=this._transferLists[t],n=r?r(e):[];return this._thread.invoke(t,e,{transferList:n,signal:s,jobPriority:i})}return this._promise?this._promise.then(()=>(n(s),this.invokeMethod(t,e,s))):Promise.reject(o())}broadcast(t,e){return this._thread?Promise.all(this._thread.broadcast(e,t)).then(l):this._promise?this._promise.then(()=>this.broadcast(t,e)):Promise.reject(o())}get promise(){return this._promise}_onClientConnected(t){}_connectListener(t){this._thread&&t.add(this._thread.on(t.eventName,t.callback))}_connectListenerToClient(t,e){t.add(e.on(t.eventName,t.callback))}}class d{constructor(t,s){this.eventName=t,this.callback=s,this._handles=new e}add(t){this._handles.add(t)}destroy(){this._handles.destroy()}}function l(){}export{a as WorkerHandle};
