"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSpacesMembersList = exports.getMembersList = exports.convertToWalletAddressList = exports.getSpaceAdminsList = exports.getAdminsList = exports.updateGroupPayload = exports.groupAccessToSpaceAccess = exports.convertRulesToSpaceRules = exports.convertSpaceRulesToRules = exports.mapSpaceListTypeToChatListType = exports.spaceDtoToSpaceInfoDto = exports.groupInfoDtoToSpaceInfoDto = exports.groupDtoToSpaceDtoV2 = exports.groupDtoToSpaceDto = exports.createGroupPayload = exports.rejectRequestPayload = exports.sendMessagePayloadCore = exports.sendMessagePayload = void 0;
const tslib_1 = require("tslib");
const helpers_1 = require("../../helpers");
const crypto_1 = require("./crypto");
const constants_1 = require("../../constants");
const pgp_1 = require("./pgp");
const AES = require("./aes");
const CryptoJS = require("crypto-js");
const getAllGroupMembers_1 = require("../getAllGroupMembers");
const pushAPITypes_1 = require("../../pushapi/pushAPITypes");
const sendMessagePayload = (receiverAddress, senderCreatedUser, messageObj, messageContent, messageType, group, env) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    return yield (0, exports.sendMessagePayloadCore)(receiverAddress, senderCreatedUser, messageObj, messageContent, messageType, group, env, pgp_1.PGPHelper);
});
exports.sendMessagePayload = sendMessagePayload;
const sendMessagePayloadCore = (receiverAddress, senderCreatedUser, messageObj, messageContent, messageType, group, env, pgpHelper) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const isGroup = !(0, helpers_1.isValidPushCAIP)(receiverAddress);
    let secretKey;
    if (isGroup && (group === null || group === void 0 ? void 0 : group.encryptedSecret) && group.sessionKey) {
        secretKey = yield (0, pgp_1.pgpDecrypt)({
            cipherText: group.encryptedSecret,
            toPrivateKeyArmored: senderCreatedUser.privateKey,
        });
    }
    else {
        secretKey = AES.generateRandomSecret(15);
    }
    const { message: encryptedMessageContent, signature: deprecatedSignature } = yield (0, crypto_1.getEncryptedRequestCore)(receiverAddress, senderCreatedUser, messageContent, isGroup, env, group, secretKey, pgpHelper);
    const { message: encryptedMessageObj, encryptionType, aesEncryptedSecret, } = yield (0, crypto_1.getEncryptedRequestCore)(receiverAddress, senderCreatedUser, JSON.stringify(messageObj), isGroup, env, group, secretKey, pgpHelper);
    const body = {
        fromDID: (0, helpers_1.walletToPCAIP10)(senderCreatedUser.wallets.split(',')[0]),
        toDID: isGroup ? receiverAddress : (0, helpers_1.walletToPCAIP10)(receiverAddress),
        fromCAIP10: (0, helpers_1.walletToPCAIP10)(senderCreatedUser.wallets.split(',')[0]),
        toCAIP10: isGroup ? receiverAddress : (0, helpers_1.walletToPCAIP10)(receiverAddress),
        messageType,
        messageObj: encryptionType === 'PlainText' ? messageObj : encryptedMessageObj,
        encType: encryptionType,
        sessionKey: group && !group.isPublic && encryptionType === 'pgpv1:group'
            ? group.sessionKey
            : null,
        encryptedSecret: aesEncryptedSecret,
        messageContent: encryptedMessageContent,
        signature: deprecatedSignature,
        sigType: 'pgpv3',
    };
    //build verificationProof
    const bodyToBeHashed = {
        fromDID: body.fromDID,
        toDID: body.fromDID,
        fromCAIP10: body.fromCAIP10,
        toCAIP10: body.toCAIP10,
        messageObj: body.messageObj,
        messageType: body.messageType,
        encType: body.encType,
        sessionKey: body.sessionKey,
        encryptedSecret: body.encryptedSecret,
    };
    const hash = CryptoJS.SHA256(JSON.stringify(bodyToBeHashed)).toString();
    const signature = yield pgpHelper.sign({
        message: hash,
        signingKey: senderCreatedUser.privateKey,
    });
    body.verificationProof = `pgpv3:${signature}`;
    return body;
});
exports.sendMessagePayloadCore = sendMessagePayloadCore;
const rejectRequestPayload = (fromDID, toDID, sigType, signature) => {
    const body = {
        fromDID,
        toDID,
        verificationProof: sigType + ':' + signature,
    };
    return body;
};
exports.rejectRequestPayload = rejectRequestPayload;
const createGroupPayload = (groupName, members, admins, isPublic, groupCreator, verificationProof, groupDescription, groupImage, contractAddressNFT, numberOfNFTs, contractAddressERC20, numberOfERC20, meta, groupType, scheduleAt, scheduleEnd, rules) => {
    const body = {
        groupName: groupName,
        groupDescription: groupDescription,
        members: members,
        groupImage: groupImage,
        admins: admins,
        isPublic: isPublic,
        contractAddressNFT: contractAddressNFT,
        numberOfNFTs: numberOfNFTs,
        contractAddressERC20: contractAddressERC20,
        numberOfERC20: numberOfERC20,
        groupCreator: groupCreator,
        verificationProof: verificationProof,
        meta: meta,
        groupType: groupType,
        scheduleAt: scheduleAt,
        scheduleEnd: scheduleEnd,
        rules: rules,
    };
    return body;
};
exports.createGroupPayload = createGroupPayload;
const groupDtoToSpaceDto = (groupDto) => {
    var _a;
    const spaceDto = {
        members: groupDto.members.map((member) => ({
            wallet: member.wallet,
            publicKey: member.publicKey,
            isSpeaker: member.isAdmin,
            image: member.image,
        })),
        pendingMembers: groupDto.pendingMembers.map((pendingMember) => ({
            wallet: pendingMember.wallet,
            publicKey: pendingMember.publicKey,
            isSpeaker: pendingMember.isAdmin,
            image: pendingMember.image,
        })),
        contractAddressERC20: groupDto.contractAddressERC20,
        numberOfERC20: groupDto.numberOfERC20,
        contractAddressNFT: groupDto.contractAddressNFT,
        numberOfNFTTokens: groupDto.numberOfNFTTokens,
        verificationProof: groupDto.verificationProof,
        spaceImage: groupDto.groupImage,
        spaceName: groupDto.groupName,
        isPublic: groupDto.isPublic,
        spaceDescription: groupDto.groupDescription,
        spaceCreator: groupDto.groupCreator,
        spaceId: groupDto.chatId,
        scheduleAt: groupDto.scheduleAt,
        scheduleEnd: groupDto.scheduleEnd,
        status: (_a = groupDto.status) !== null && _a !== void 0 ? _a : null,
        meta: groupDto.meta,
    };
    if (groupDto.rules) {
        spaceDto.rules = {
            entry: groupDto.rules.entry,
        };
    }
    return spaceDto;
};
exports.groupDtoToSpaceDto = groupDtoToSpaceDto;
const groupDtoToSpaceDtoV2 = (groupDto, env = constants_1.ENV.PROD) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const members = yield (0, getAllGroupMembers_1.getAllGroupMembers)({
        chatId: groupDto.chatId,
        env: env,
    });
    const spaceDto = {
        members: members
            .filter((member) => member.intent)
            .map((member) => {
            var _a, _b;
            return ({
                wallet: member.address,
                publicKey: (_a = member.userInfo.publicKey) !== null && _a !== void 0 ? _a : '',
                isSpeaker: member.role === 'admin',
                image: (_b = member.userInfo.profile.picture) !== null && _b !== void 0 ? _b : '',
            });
        }),
        pendingMembers: members
            .filter((member) => !member.intent)
            .map((pendingMember) => {
            var _a, _b;
            return ({
                wallet: pendingMember.address,
                publicKey: (_a = pendingMember.userInfo.publicKey) !== null && _a !== void 0 ? _a : '',
                isSpeaker: pendingMember.role === 'admin',
                image: (_b = pendingMember.userInfo.profile.picture) !== null && _b !== void 0 ? _b : '',
            });
        }),
        contractAddressERC20: null,
        numberOfERC20: 0,
        contractAddressNFT: null,
        numberOfNFTTokens: 0,
        verificationProof: 'a',
        spaceImage: groupDto.groupImage,
        spaceName: groupDto.groupName,
        isPublic: groupDto.isPublic,
        spaceDescription: groupDto.groupDescription,
        spaceCreator: groupDto.groupCreator,
        spaceId: groupDto.chatId,
        scheduleAt: groupDto.scheduleAt,
        scheduleEnd: groupDto.scheduleEnd,
        status: (_a = groupDto.status) !== null && _a !== void 0 ? _a : null,
        meta: groupDto.meta,
    };
    if (groupDto.rules) {
        spaceDto.rules = {
            entry: groupDto.rules.entry,
        };
    }
    return spaceDto;
});
exports.groupDtoToSpaceDtoV2 = groupDtoToSpaceDtoV2;
const groupInfoDtoToSpaceInfoDto = (groupInfoDto) => {
    var _a, _b, _c, _d, _e;
    const spaceInfoDto = {
        spaceName: groupInfoDto.groupName,
        spaceImage: groupInfoDto.groupImage,
        spaceDescription: groupInfoDto.groupDescription,
        isPublic: groupInfoDto.isPublic,
        spaceCreator: groupInfoDto.groupCreator,
        spaceId: groupInfoDto.chatId,
        scheduleAt: groupInfoDto.scheduleAt,
        scheduleEnd: groupInfoDto.scheduleEnd,
        status: (_a = groupInfoDto.status) !== null && _a !== void 0 ? _a : null,
        rules: (_b = groupInfoDto.rules) !== null && _b !== void 0 ? _b : null,
        meta: (_c = groupInfoDto.meta) !== null && _c !== void 0 ? _c : null,
        sessionKey: (_d = groupInfoDto.sessionKey) !== null && _d !== void 0 ? _d : null,
        encryptedSecret: (_e = groupInfoDto.encryptedSecret) !== null && _e !== void 0 ? _e : null,
    };
    return spaceInfoDto;
};
exports.groupInfoDtoToSpaceInfoDto = groupInfoDtoToSpaceInfoDto;
const spaceDtoToSpaceInfoDto = (spaceDto) => {
    return {
        spaceName: spaceDto.spaceName,
        spaceImage: spaceDto.spaceImage,
        spaceDescription: spaceDto.spaceDescription,
        isPublic: spaceDto.isPublic,
        spaceCreator: spaceDto.spaceCreator,
        spaceId: spaceDto.spaceId,
        scheduleAt: spaceDto.scheduleAt,
        scheduleEnd: spaceDto.scheduleEnd,
        status: spaceDto.status,
        rules: spaceDto.rules,
        meta: spaceDto.meta,
        sessionKey: null,
        encryptedSecret: null,
        inviteeDetails: spaceDto.inviteeDetails,
    };
};
exports.spaceDtoToSpaceInfoDto = spaceDtoToSpaceInfoDto;
const mapSpaceListTypeToChatListType = (type) => {
    switch (type) {
        case pushAPITypes_1.SpaceListType.SPACES:
            return pushAPITypes_1.ChatListType.CHATS;
        case pushAPITypes_1.SpaceListType.REQUESTS:
            return pushAPITypes_1.ChatListType.REQUESTS;
        default:
            throw new Error(`Unsupported SpaceListType: ${type}`);
    }
};
exports.mapSpaceListTypeToChatListType = mapSpaceListTypeToChatListType;
const convertSpaceRulesToRules = (spaceRules) => {
    return {
        entry: spaceRules.entry,
        chat: undefined,
    };
};
exports.convertSpaceRulesToRules = convertSpaceRulesToRules;
const convertRulesToSpaceRules = (rules) => {
    return {
        entry: rules.entry,
    };
};
exports.convertRulesToSpaceRules = convertRulesToSpaceRules;
const groupAccessToSpaceAccess = (group) => {
    const spaceAccess = {
        entry: group.entry,
    };
    // If rules are present in the entry, map them to the spaceAccess
    if (group.rules) {
        spaceAccess.rules = (0, exports.convertRulesToSpaceRules)(group.rules);
    }
    return spaceAccess;
};
exports.groupAccessToSpaceAccess = groupAccessToSpaceAccess;
const updateGroupPayload = (groupName, members, admins, address, verificationProof, encryptedSecret, groupDescription, groupImage, scheduleAt, scheduleEnd, status, meta, rules) => {
    const body = Object.assign(Object.assign({ groupName: groupName, groupImage: groupImage, groupDescription: groupDescription, members: members, admins: admins, address: address, verificationProof: verificationProof, encryptedSecret: encryptedSecret, scheduleAt: scheduleAt, scheduleEnd: scheduleEnd, status: status }, (meta !== undefined && { meta: meta })), (rules !== undefined && { rules: rules }));
    return body;
};
exports.updateGroupPayload = updateGroupPayload;
// helper.ts
const getAdminsList = (members, pendingMembers) => {
    const adminsFromMembers = members
        ? (0, exports.convertToWalletAddressList)(members.filter((admin) => admin.isAdmin))
        : [];
    const adminsFromPendingMembers = pendingMembers
        ? (0, exports.convertToWalletAddressList)(pendingMembers.filter((admin) => admin.isAdmin))
        : [];
    const adminList = [...adminsFromMembers, ...adminsFromPendingMembers];
    return adminList;
};
exports.getAdminsList = getAdminsList;
const getSpaceAdminsList = (members, pendingMembers) => {
    const adminsFromMembers = members
        ? (0, exports.convertToWalletAddressList)(members.filter((admin) => admin.isSpeaker))
        : [];
    const adminsFromPendingMembers = pendingMembers
        ? (0, exports.convertToWalletAddressList)(pendingMembers.filter((admin) => admin.isSpeaker))
        : [];
    const adminList = [...adminsFromMembers, ...adminsFromPendingMembers];
    return adminList;
};
exports.getSpaceAdminsList = getSpaceAdminsList;
const convertToWalletAddressList = (memberList) => {
    return memberList ? memberList.map((member) => member.wallet) : [];
};
exports.convertToWalletAddressList = convertToWalletAddressList;
const getMembersList = (members, pendingMembers) => {
    const allMembers = [...(members || []), ...(pendingMembers || [])];
    return (0, exports.convertToWalletAddressList)(allMembers);
};
exports.getMembersList = getMembersList;
const getSpacesMembersList = (members, pendingMembers) => {
    const allMembers = [...(members || []), ...(pendingMembers || [])];
    return (0, exports.convertToWalletAddressList)(allMembers);
};
exports.getSpacesMembersList = getSpacesMembersList;
//# sourceMappingURL=payloadHelper.js.map