"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.waitForStorage = void 0;
const protocol_1 = require("@streamr/protocol");
const utils_1 = require("@streamr/utils");
const Message_1 = require("../Message");
const StreamrClientError_1 = require("../StreamrClientError");
const logger = new utils_1.Logger(module);
const waitForStorage = async (message, opts, resends, streamStorageRegistry) => {
    if (!message) {
        throw new StreamrClientError_1.StreamrClientError('waitForStorage requires a Message', 'INVALID_ARGUMENT');
    }
    const matcher = opts.messageMatchFn ?? ((msgTarget, msgGot) => ((0, utils_1.areEqualBinaries)(msgTarget.signature, msgGot.signature)));
    const start = Date.now();
    let last;
    let found = false;
    while (!found) {
        const duration = Date.now() - start;
        if (duration > opts.timeout) {
            logger.debug('Timed out waiting for storage to contain message', {
                expected: message.streamMessage.messageId,
                lastReceived: last?.map((l) => l.messageId),
            });
            throw new Error(`timed out after ${duration}ms waiting for message`);
        }
        const getStorageNodes = (streamId) => streamStorageRegistry.getStorageNodes(streamId);
        const resendStream = await resends.resend((0, protocol_1.toStreamPartID)(message.streamId, message.streamPartition), { last: opts.count }, getStorageNodes);
        last = await (0, utils_1.collect)(resendStream);
        for (const lastMsg of last) {
            if (matcher(message, (0, Message_1.convertStreamMessageToMessage)(lastMsg))) {
                found = true;
                logger.debug('Found matching message');
                return;
            }
        }
        logger.debug('Retry after delay (matching message not found)', {
            expected: message.streamMessage.messageId,
            'last-3': last.slice(-3).map((l) => l.messageId),
            delayInMs: opts.interval
        });
        await (0, utils_1.wait)(opts.interval);
    }
    /* eslint-enable no-await-in-loop */
};
exports.waitForStorage = waitForStorage;
//# sourceMappingURL=waitForStorage.js.map