"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeBridgeCacheSystem = void 0;
const cache_1 = require("@ledgerhq/live-network/cache");
const _1 = require("./");
const defaultCacheStrategy = {
    preloadMaxAge: 5 * 60 * 1000,
};
function makeBridgeCacheSystem({ saveData, getData, }) {
    const hydrateCurrency = async (currency) => {
        const value = await getData(currency);
        const bridge = (0, _1.getCurrencyBridge)(currency);
        bridge.hydrate(value, currency);
        return value;
    };
    const lruCaches = {};
    const prepareCurrency = async (currency, { forceUpdate } = { forceUpdate: false }) => {
        const bridge = (0, _1.getCurrencyBridge)(currency);
        const { preloadMaxAge } = {
            ...defaultCacheStrategy,
            ...(bridge.getPreloadStrategy && bridge.getPreloadStrategy(currency)),
        };
        let cache = lruCaches[currency.id];
        if (!cache || forceUpdate) {
            cache = (0, cache_1.makeLRUCache)(async () => {
                const preloaded = await bridge.preload(currency);
                if (preloaded) {
                    bridge.hydrate(preloaded, currency);
                    await saveData(currency, preloaded);
                }
                return preloaded;
            }, () => "", {
                ttl: preloadMaxAge,
            });
            lruCaches[currency.id] = cache;
        }
        return cache();
    };
    return {
        hydrateCurrency,
        prepareCurrency,
    };
}
exports.makeBridgeCacheSystem = makeBridgeCacheSystem;
//# sourceMappingURL=cache.js.map