"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addDeprecatedInfoToMessages = exports.addDeprecatedInfo = exports.decryptConversation = exports.getTrendingSpaceInboxLists = exports.getSpaceInboxLists = exports.getInboxLists = void 0;
const tslib_1 = require("tslib");
const constants_1 = require("../../constants");
const helpers_1 = require("../../helpers");
const user_1 = require("../../user");
const ipfs_1 = require("../ipfs");
const crypto_1 = require("./crypto");
const getInboxLists = (options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const { lists, user, toDecrypt, pgpPrivateKey, env = constants_1.default.ENV.PROD, } = options || {};
    const connectedUser = yield (0, user_1.get)({ account: (0, helpers_1.pCAIP10ToWallet)(user), env });
    const feeds = [];
    for (const list of lists) {
        let message;
        if (list.threadhash !== null) {
            message = yield (0, ipfs_1.getCID)(list.threadhash, { env });
        }
        // This is for groups that are created without any message
        else {
            message = {
                encType: 'PlainText',
                encryptedSecret: '',
                fromCAIP10: '',
                fromDID: '',
                link: '',
                messageContent: '',
                messageType: '',
                sigType: '',
                signature: '',
                toCAIP10: '',
                toDID: '',
            };
        }
        feeds.push(Object.assign(Object.assign({}, list), { msg: message, groupInformation: list.groupInformation }));
    }
    if (toDecrypt)
        return (0, crypto_1.decryptFeeds)({ feeds, connectedUser, pgpPrivateKey, env });
    return feeds;
});
exports.getInboxLists = getInboxLists;
const getSpaceInboxLists = (options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const { lists, user, toDecrypt, pgpPrivateKey, env = constants_1.default.ENV.PROD, } = options || {};
    const connectedUser = yield (0, user_1.get)({ account: (0, helpers_1.pCAIP10ToWallet)(user), env });
    const feeds = [];
    for (const list of lists) {
        let message;
        if (list.threadhash !== null) {
            message = yield (0, ipfs_1.getCID)(list.threadhash, { env });
        }
        // This is for groups that are created without any message
        else {
            message = {
                encType: 'PlainText',
                encryptedSecret: '',
                fromCAIP10: '',
                fromDID: '',
                link: '',
                messageContent: '',
                messageType: '',
                sigType: '',
                signature: '',
                toCAIP10: '',
                toDID: '',
            };
        }
        feeds.push(Object.assign(Object.assign({}, list), { msg: message, spaceInformation: list.spaceInformation }));
    }
    if (toDecrypt)
        return (0, crypto_1.decryptFeeds)({ feeds, connectedUser, pgpPrivateKey, env });
    return feeds;
});
exports.getSpaceInboxLists = getSpaceInboxLists;
const getTrendingSpaceInboxLists = (options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const { lists, env = constants_1.default.ENV.PROD } = options || {};
    const feeds = [];
    for (const list of lists) {
        let message;
        if (list.threadhash !== null) {
            message = yield (0, ipfs_1.getCID)(list.threadhash, { env });
        }
        // This is for groups that are created without any message
        else {
            message = {
                encType: 'PlainText',
                encryptedSecret: '',
                fromCAIP10: '',
                fromDID: '',
                link: '',
                messageContent: '',
                messageType: '',
                sigType: '',
                signature: '',
                toCAIP10: '',
                toDID: '',
            };
        }
        feeds.push(Object.assign(Object.assign({}, list), { msg: message, spaceInformation: list.spaceInformation }));
    }
    return feeds;
});
exports.getTrendingSpaceInboxLists = getTrendingSpaceInboxLists;
const decryptConversation = (options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const { messages, connectedUser, pgpPrivateKey, env = constants_1.default.ENV.PROD, } = options || {};
    let otherPeer;
    let signatureValidationPubliKey; // To do signature verification it depends on who has sent the message
    for (let i = 0; i < messages.length; i++) {
        const message = messages[i];
        let gotOtherPeer = false;
        if (message.encType !== 'PlainText') {
            // check if message is already decrypted
            if (
            // legacy messages ( no way to know if they are decrypted or not )
            message.messageObj === undefined ||
                // new messages ( if messageObj is string then it is not decrypted )
                typeof message.messageObj === 'string') {
                if (!pgpPrivateKey) {
                    throw Error('Decrypted private key is necessary');
                }
                if (message.fromCAIP10 !== connectedUser.wallets.split(',')[0]) {
                    if (!gotOtherPeer) {
                        otherPeer = yield (0, user_1.get)({ account: message.fromCAIP10, env });
                        gotOtherPeer = true;
                    }
                    signatureValidationPubliKey = otherPeer.publicKey;
                }
                else {
                    signatureValidationPubliKey = connectedUser.publicKey;
                }
                messages[i] = yield (0, crypto_1.decryptAndVerifyMessage)(message, signatureValidationPubliKey, pgpPrivateKey, env);
            }
        }
    }
    return messages;
});
exports.decryptConversation = decryptConversation;
//immediately invoked function expression to maintain latestDIDs
exports.addDeprecatedInfo = (() => {
    // mapping for LAtest NFT DIDs
    const latestDIDs = {};
    return (chats) => {
        chats.forEach((chat) => {
            if ((0, helpers_1.isValidCAIP10NFTAddress)(chat.did)) {
                const didWithoutTimestamp = chat.did.split(':').slice(0, 5).join(':');
                const timestamp = chat.did.split(':')[5];
                if (!latestDIDs[didWithoutTimestamp] ||
                    timestamp > latestDIDs[didWithoutTimestamp].split(':')[5]) {
                    latestDIDs[didWithoutTimestamp] = chat.did;
                }
            }
        });
        chats.forEach((chat) => {
            if ((0, helpers_1.isValidCAIP10NFTAddress)(chat.did)) {
                const didWithoutTimestamp = chat.did.split(':').slice(0, 5).join(':');
                if (latestDIDs[didWithoutTimestamp] !== chat.did) {
                    chat['deprecated'] = true;
                    chat['deprecatedCode'] = 'NFT Owner Changed';
                }
            }
        });
        return chats;
    };
})();
//immediately invoked function expression to maintain latestDIDs
exports.addDeprecatedInfoToMessages = (() => {
    // mapping for LAtest NFT DIDs
    const latestDIDs = {};
    return (chats) => {
        chats.forEach((chat) => {
            if ((0, helpers_1.isValidCAIP10NFTAddress)(chat.fromDID)) {
                const didWithoutTimestamp = chat.fromDID
                    .split(':')
                    .slice(0, 5)
                    .join(':');
                const timestamp = chat.fromDID.split(':')[5];
                if (!latestDIDs[didWithoutTimestamp] ||
                    timestamp > latestDIDs[didWithoutTimestamp].split(':')[5]) {
                    latestDIDs[didWithoutTimestamp] = chat.fromDID;
                }
            }
        });
        chats.forEach((chat) => {
            if ((0, helpers_1.isValidCAIP10NFTAddress)(chat.fromDID)) {
                const didWithoutTimestamp = chat.fromDID
                    .split(':')
                    .slice(0, 5)
                    .join(':');
                if (latestDIDs[didWithoutTimestamp] !== chat.fromDID) {
                    chat['deprecated'] = true;
                    chat['deprecatedCode'] = 'NFT Owner Changed';
                }
            }
        });
        return chats;
    };
})();
//# sourceMappingURL=inbox.js.map