"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCachedBlockForTimestamp = void 0;
var tslib_1 = require("tslib");
var TypeGuards_1 = require("./TypeGuards");
var TimeUtils_1 = require("./TimeUtils");
var CachingUtils_1 = require("./CachingUtils");
var constants_1 = require("../constants");
function getCachedBlockForTimestamp(chainId, timestamp, blockFinder, cache, hints) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var resolver, key, result, blockNumber;
        var _this = this;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    resolver = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4, blockFinder.getBlockForTimestamp(timestamp, hints || {})];
                            case 1: return [2, (_a.sent()).number];
                        }
                    }); }); };
                    if (!(0, TypeGuards_1.isDefined)(cache)) {
                        return [2, resolver()];
                    }
                    key = "".concat(chainId, "_block_number_").concat(timestamp);
                    if (!(0, CachingUtils_1.shouldCache)(timestamp, (0, TimeUtils_1.getCurrentTime)(), constants_1.DEFAULT_CACHING_SAFE_LAG)) return [3, 6];
                    return [4, cache.get(key)];
                case 1:
                    result = _a.sent();
                    if (!(result !== null)) return [3, 2];
                    return [2, parseInt(result)];
                case 2: return [4, resolver()];
                case 3:
                    blockNumber = _a.sent();
                    return [4, cache.set(key, blockNumber.toString(), 60 * 60 * 24 * 90)];
                case 4:
                    _a.sent();
                    return [2, blockNumber];
                case 5: return [3, 7];
                case 6: return [2, resolver()];
                case 7: return [2];
            }
        });
    });
}
exports.getCachedBlockForTimestamp = getCachedBlockForTimestamp;
//# sourceMappingURL=BlockUtils.js.map