import { fsa } from '@basemaps/shared';
import { CogTiff } from '@cogeotiff/core';
import { Cotar } from '@cotar/core';
import { St } from './source.tracer.js';
import { SwappingLru } from './swapping.lru.js';
class LruStrutObj {
    constructor(ob) {
        this.ob = ob;
        if (this.ob._value == null)
            this.ob.value.then((c) => (this.ob._value = c));
    }
    get size() {
        const val = this.ob._value;
        if (val == null)
            return 0;
        return val.source.chunkSize * val.source.chunks.size;
    }
}
export class SourceCache {
    constructor(maxSize) {
        this.cache = new SwappingLru(maxSize);
    }
    getCog(location) {
        var _a;
        const existing = (_a = this.cache.get(location)) === null || _a === void 0 ? void 0 : _a.ob;
        if (existing != null) {
            if (existing.type === 'cog')
                return existing.value;
            throw new Error(`Existing object of type: ${existing.type} made for location: ${location}`);
        }
        const source = fsa.source(location);
        St.trace(source);
        const value = CogTiff.create(source);
        this.cache.set(location, new LruStrutObj({ type: 'cog', value }));
        return value;
    }
    getCotar(location) {
        var _a;
        const existing = (_a = this.cache.get(location)) === null || _a === void 0 ? void 0 : _a.ob;
        if (existing != null) {
            if (existing.type === 'cotar')
                return existing.value;
            throw new Error(`Existing object of type: ${existing.type} made for location: ${location}`);
        }
        const source = fsa.source(location);
        St.trace(source);
        const value = Cotar.fromTar(source);
        this.cache.set(location, new LruStrutObj({ type: 'cotar', value }));
        return value;
    }
}
/** Approx ~1.4GB 2x~700MB caches */
export const CoSources = new SourceCache(700 * 1000 * 1000);
//# sourceMappingURL=source.cache.js.map