/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import{handlesGroup as e}from"../handleUtils.js";import"../has.js";import{isPromiseLike as t,createAbortError as s,createResolver as i,throwIfAborted as o}from"../promiseUtils.js";import n from"../Queue.js";import{unregister as r}from"./connectionRegistry.js";import{createInvokeProxy as l}from"./InvokeHandler.js";import h from"./RemoteClient.js";class c{constructor(){this._inUseClients=new Array,this._clients=new Array,this._clientPromises=new Array,this._ongoingJobsQueue=new n,this._ongoingLowPriorityJobsQueue=new n}destroy(){this.close()}get closed(){return!this._clients?.length}open(e,s){return new Promise((i,n)=>{let r=!0;const l=e=>{o(s.signal),r&&(r=!1,e())};this._clients.length=e.length,this._clientPromises.length=e.length,this._inUseClients.length=e.length;for(let o=0;o<e.length;++o){const r=e[o];t(r)?this._clientPromises[o]=r.then(e=>(this._clients[o]=new h(e,s,this._ongoingJobsQueue,this._ongoingLowPriorityJobsQueue),l(i),this._clients[o]),()=>(l(n),null)):(this._clients[o]=new h(r,s,this._ongoingJobsQueue,this._ongoingLowPriorityJobsQueue),this._clientPromises[o]=Promise.resolve(this._clients[o]),l(i))}})}broadcast(e,t,s){const i=new Array(this._clientPromises.length);for(let o=0;o<this._clientPromises.length;++o){const n=this._clientPromises[o];i[o]=n.then(i=>i?.invoke(e,t,s))}return i}close(){let e;for(;e=this._ongoingJobsQueue.pop();)e.resolver.reject(s(`Worker closing, aborting job calling '${e.methodName}'`));for(;e=this._ongoingLowPriorityJobsQueue.pop();)e.resolver.reject(s(`Worker closing, aborting job calling '${e.methodName}'`));for(const t of this._clientPromises)t.then(e=>e?.close());this._clients.length=0,this._clientPromises.length=0,this._inUseClients.length=0,r(this)}invoke(e,t,s){return this.apply(e,[t],s)}apply(e,t,s){const o=i();(1===s?.jobPriority?this._ongoingLowPriorityJobsQueue:this._ongoingJobsQueue).push({methodName:e,data:t,invokeOptions:s,resolver:o});for(let i=0;i<this._clientPromises.length;i++){const e=this._clients[i];e?e.jobAdded():this._clientPromises[i].then(e=>e?.jobAdded())}return o.promise}createInvokeProxy(e){return l(this,e)}on(t,s){return Promise.all(this._clientPromises).then(()=>e(this._clients.map(e=>e.on(t,s))))}openPorts(){return new Promise(e=>{const t=new Array(this._clientPromises.length);let s=t.length;for(let i=0;i<this._clientPromises.length;++i){this._clientPromises[i].then(o=>{o&&(t[i]=o.openPort()),0===--s&&e(t)})}})}get test(){}}export{c as default};
