"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decrypt = void 0;
const protocol_1 = require("@streamr/protocol");
const EncryptionUtil_1 = require("../encryption/EncryptionUtil");
// 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 (e) {
        if (destroySignal.isDestroyed()) {
            return streamMessage;
        }
        throw new EncryptionUtil_1.DecryptError(streamMessage, `Could not get GroupKey ${streamMessage.groupKeyId}: ${e.message}`);
    }
    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 protocol_1.StreamMessage({
        ...streamMessage,
        content,
        encryptionType: protocol_1.EncryptionType.NONE
    });
};
exports.decrypt = decrypt;
//# sourceMappingURL=decrypt.js.map