"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decrypt = void 0;
const trackerless_network_1 = require("@streamr/trackerless-network");
const EncryptionUtil_1 = require("../encryption/EncryptionUtil");
const StreamMessage_1 = require("../protocol/StreamMessage");
const StreamrClientError_1 = require("../StreamrClientError");
// TODO if this.destroySignal.isDestroyed() is true, would it make sense to reject the promise
// and not to return the original encrypted message?
// - e.g. StoppedError, which is not visible to end-user
const decrypt = async (streamMessage, groupKeyManager, destroySignal) => {
    if (destroySignal.isDestroyed()) {
        return streamMessage;
    }
    let groupKey;
    try {
        groupKey = await groupKeyManager.fetchKey(streamMessage.getStreamPartID(), streamMessage.groupKeyId, streamMessage.getPublisherId());
    }
    catch {
        if (destroySignal.isDestroyed()) {
            return streamMessage;
        }
        throw new StreamrClientError_1.StreamrClientError(`Could not get encryption key ${streamMessage.groupKeyId}`, 'DECRYPT_ERROR', streamMessage);
    }
    if (destroySignal.isDestroyed()) {
        return streamMessage;
    }
    const [content, newGroupKey] = EncryptionUtil_1.EncryptionUtil.decryptStreamMessage(streamMessage, groupKey);
    if (newGroupKey !== undefined) {
        await groupKeyManager.addKeyToLocalStore(newGroupKey, streamMessage.getPublisherId());
    }
    return new StreamMessage_1.StreamMessage({
        ...streamMessage,
        content,
        encryptionType: trackerless_network_1.EncryptionType.NONE
    });
};
exports.decrypt = decrypt;
//# sourceMappingURL=decrypt.js.map