/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import{__decorate as e}from"tslib";import t from"../../../../core/Accessor.js";import{EventEmitter as r}from"../../../../core/Evented.js";import s from"../../../../core/Logger.js";import{isPromiseLike as o,isAbortError as i}from"../../../../core/promiseUtils.js";import{property as n,subclass as u}from"../../../../core/accessorSupport/decorators.js";import{isUpdatableTexture as a}from"./IManagedTexture.js";import{TextureUpdater as d}from"./TextureUpdater.js";import{TaskPriority as h}from"../../../support/Scheduler.js";let l=class extends t{constructor(e){super({}),this._stage=e,this._textures=new Map,this._loadingCount=0,this.events=new r,this.updater=new d,this._frameTask=e.view.resourceController.scheduler.registerTask(h.TEXTURE_UNLOAD)}normalizeCtorArgs(){return{}}destroy(){this._frameTask.remove(),this.updater.destroy(),this._textures.forEach(e=>e.unload())}get updating(){return this._loadingCount>0||this._frameTask.updating}acquire(e){const t=this._textures.get(e);return t?(t.ref(),t.loadingPromise??t):this._createNewRef(e)}update(){this.updater.run()&&this.events.emit("changed",0)}_createNewRef(e){const t=this._stage.getTexture(e);if(null==t)return null;const r=t.events.on("unloaded",()=>{r.remove(),this._onTextureUnloaded(t)}),n=new g(t,()=>{this._frameTask.schedule(()=>{n.isUnreferenced&&t.unload()})});return this._textures.set(e,n),n.ref(),t.loaded?(this._updateGLTexture(n,t.texture),a(t)&&this.updater.add(t),n):(this._loadingCount++,n.loadingPromise=this._stage.schedule(()=>{const e=t.load(this._stage.renderView.renderingContext),r=e=>(this._loadingCount--,n.loadingPromise=null,this._updateGLTexture(n,e),a(t)&&this.updater.add(t),n),u=e=>(t.unload(),this._loadingCount--,n.loadingPromise=null,i(e)||s.getLogger(this).error(e),null);return o(e)?e.then(r,u):r(e)}),n.loadingPromise)}_updateGLTexture(e,t){e.texture=t,this.events.emit("changed",1)}_onTextureUnloaded(e){this._textures.delete(e.id),this.updater.remove(e)}};e([n()],l.prototype,"_loadingCount",void 0),e([n()],l.prototype,"_frameTask",void 0),e([n()],l.prototype,"updating",null),l=e([u("esri.views.3d.webgl-engine.lib.TextureRepository")],l);class g{constructor(e,t){this._texture=e,this._release=t,this._refCount=0}get id(){return this._texture.id}get isUnreferenced(){return 0===this._refCount}ref(){++this._refCount}release(){--this._refCount,this._refCount>0||(0!==this._refCount?(s.getLogger("esri.views.3d.webgl-engine.lib.TextureRepository.RefCountedTextureImpl").error("Cannot dereference texture that has no references!"),this._refCount=0):this._release())}unload(){this._texture.unload()}}export{l as TextureRepository};
