import{getLogger as i}from"../utilities/log.js";import{parallelEach as e}from"../utilities/promise.js";import{InitializeError as t}from"./InitializeError.js";import{SerializableBase as r}from"./Serializable.js";import{notifyChange as s,observable as a}from"./observableUtils.js";export class InitializableBase extends(a(r)){get isInitialized(){return this._isInitialized}get isDestroyed(){return this._isDestroyed}get failureMode(){return this._failureMode}set failureMode(i){this._failureMode=i}_isInitialized=!1;_isDestroyed=!1;_initializePromise;_destroyPromise;_failureMode="warn";async initialize(){return void 0===this._initializePromise&&(this._initializePromise=(async()=>{try{await this.finishAssignProperties(),await this._onInitialize(),await this._initializeChildren(),await this._postInitialize()}catch(i){throw i instanceof Error?(this._initializePromise=void 0,new t(this.failureMode,i,this)):i}this._isInitialized=!0,s(this,"isInitialized")})()),this._initializePromise}async destroy(){return void 0===this._destroyPromise&&(this._destroyPromise=(async()=>{try{await this._onDestroy()}catch(i){throw this._destroyPromise=void 0,i}this._isDestroyed=!0,s(this,"isDestroyed")})()),this._destroyPromise}toJSON(i="all"){return super.toJSON(i)}assignProperties(i){super.assignProperties(i)}assignPropertiesAsync(i){return super.assignPropertiesAsync(i)}getDefaults(){return super.getDefaults()}getDefault(i){return super.getDefault(i)}getSerializableProperties(i){return super.getSerializableProperties(i)}_getSerializableProperties(){return{...super._getSerializableProperties(),failureMode:{serializeModes:["initial"],default:"warn"}}}async _onInitialize(){}async _postInitialize(){}async _onDestroy(){}async _initializeChildren(){await e(this._initializableChildCollections(),(i=>initializeCollection(i,{target:this,onInitializeWarning:i=>this.emit("initializeWarning",i)})))}*_initializableChildCollections(){}}const o={onInitializeWarning:()=>{}};export async function initializeCollection(r,s=o){const{onInitializeWarning:a,target:n}=s;await e(r.toArray(),(async e=>{const r=e.on("initializeWarning",a);try{await e.initialize()}catch(r){const s=r instanceof t?r:new t(e.failureMode,r,e);if("error"===s.failureMode)throw s;"warn"===s.failureMode&&i("geocortex.api.support.InitializeBase").warn({message:"Error attempting to initialize child item: {0}.",error:s},s.error.message);a({error:s,target:n})}finally{r.remove()}}))}