"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LayeredCache = void 0;
const createCacheTimestampComparator_1 = require("./createCacheTimestampComparator");
const DiskCache_1 = require("./DiskCache");
const MemoryCache_1 = require("./MemoryCache");
class LayeredCache {
    constructor() {
        this.layers = [new MemoryCache_1.MemoryCache(), new DiskCache_1.DiskCache()];
    }
    async get(locale) {
        const cache = this.getLastModifiedLayer(locale);
        if (!cache) {
            return Promise.resolve(undefined);
        }
        const [memoryCache, diskCache] = this.layers;
        const value = await cache.get(locale);
        if (cache === diskCache && typeof value !== 'undefined') {
            await memoryCache.set(locale, value);
        }
        return value;
    }
    getLastModifiedTimestamp(locale) {
        const cache = this.getLastModifiedLayer(locale);
        if (!cache) {
            return undefined;
        }
        return cache.getLastModifiedTimestamp(locale);
    }
    has(locale) {
        return this.layers.some((cache) => cache.has(locale));
    }
    isStale(locale) {
        if (this.layers.some((cache) => cache.isStale(locale))) {
            return true;
        }
        if (this.layers.every((cache) => typeof cache.isStale(locale) === 'undefined')) {
            return undefined;
        }
        return false;
    }
    async set(locale, trie) {
        const [memoryCache, diskCache] = this.layers;
        await diskCache.set(locale, trie);
        await memoryCache.set(locale, trie);
    }
    getLastModifiedLayer(locale) {
        const layers = this.layers.filter((cache) => cache.has(locale));
        const [cached] = [...layers].sort((0, createCacheTimestampComparator_1.createCacheTimestampComparator)(locale));
        return cached;
    }
}
exports.LayeredCache = LayeredCache;
