import { makeLRUCache } from "@ledgerhq/live-network/cache";
import { getCurrencyBridge } from "./";
const defaultCacheStrategy = {
    preloadMaxAge: 5 * 60 * 1000,
};
export function makeBridgeCacheSystem({ saveData, getData, }) {
    const hydrateCurrency = async (currency) => {
        const value = await getData(currency);
        const bridge = getCurrencyBridge(currency);
        bridge.hydrate(value, currency);
        return value;
    };
    const lruCaches = {};
    const prepareCurrency = async (currency, { forceUpdate } = { forceUpdate: false }) => {
        const bridge = getCurrencyBridge(currency);
        const { preloadMaxAge } = {
            ...defaultCacheStrategy,
            ...(bridge.getPreloadStrategy && bridge.getPreloadStrategy(currency)),
        };
        let cache = lruCaches[currency.id];
        if (!cache || forceUpdate) {
            cache = 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,
    };
}
//# sourceMappingURL=cache.js.map