"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Space = void 0;
const tslib_1 = require("tslib");
const pushAPITypes_1 = require("./pushAPITypes");
const PUSH_SPACE = require("../space");
const PUSH_CHAT = require("../chat");
const PushAPI_1 = require("./PushAPI");
const updateGroupProfile_1 = require("../chat/updateGroupProfile");
const updateGroupConfig_1 = require("../chat/updateGroupConfig");
const chat_1 = require("../chat");
const helpers_1 = require("../helpers");
const chat_2 = require("./chat");
const helpers_2 = require("../helpers");
const SpaceV2_1 = require("../space/SpaceV2");
const Space_1 = require("../space/Space");
class Space {
    constructor(account, env, decryptedPgpPvtKey, signer, progressHook) {
        this.account = account;
        this.env = env;
        this.decryptedPgpPvtKey = decryptedPgpPvtKey;
        this.signer = signer;
        this.progressHook = progressHook;
        this.participants = {
            list: (chatId, options) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                const { page = 1, limit = 20 } = options !== null && options !== void 0 ? options : {};
                const getGroupMembersOptions = {
                    chatId,
                    page,
                    limit,
                    env: this.env,
                };
                const chatMembers = yield PUSH_CHAT.getGroupMembers(getGroupMembersOptions);
                const members = chatMembers.map((member) => {
                    return {
                        address: member.address,
                        intent: member.intent,
                        role: member.role.toUpperCase() === 'ADMIN' ? 'SPEAKER' : 'LISTENER',
                        userInfo: member.userInfo,
                    };
                });
                return { members };
            }),
            count: (chatId) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                const count = yield PUSH_CHAT.getGroupMemberCount({
                    chatId,
                    env: this.env,
                });
                return {
                    participants: count.overallCount - count.pendingCount,
                    pending: count.pendingCount,
                };
            }),
            status: (chatId, accountId) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                const status = yield PUSH_CHAT.getGroupMemberStatus({
                    chatId: chatId,
                    did: accountId,
                    env: this.env,
                });
                return {
                    pending: status.isPending,
                    role: status.isAdmin ? 'SPEAKER' : 'LISTENER',
                    participant: status.isMember,
                };
            }),
        };
        this.chatInstance = new chat_2.Chat(this.account, this.env, { feature: [] }, this.decryptedPgpPvtKey, this.signer);
    }
    create(name, options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error('Signer is required to create a space.');
            }
            const createSpaceOptions = {
                signer: this.signer,
                pgpPrivateKey: this.decryptedPgpPvtKey,
                spaceName: name,
                spaceDescription: options.description || null,
                listeners: options.participants.listeners,
                speakers: options.participants.speakers,
                spaceImage: options.image || null,
                isPublic: !options.private,
                rules: options.rules || {},
                config: {
                    scheduleAt: options.schedule.start,
                    scheduleEnd: options.schedule.end || null,
                },
                env: this.env,
            };
            return yield PUSH_SPACE.createV2(createSpaceOptions);
        });
    }
    update(spaceId, options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
            }
            let group = null;
            try {
                group = yield PUSH_CHAT.getGroupInfo({
                    chatId: spaceId,
                    env: this.env,
                });
                if (!group) {
                    throw new Error('Space not found');
                }
            }
            catch (error) {
                throw new Error('Space not found');
            }
            const updateGroupProfileOptions = {
                chatId: spaceId,
                groupName: options.name ? options.name : group.groupName,
                groupDescription: options.description
                    ? options.description
                    : group.groupDescription,
                groupImage: options.image ? options.image : group.groupImage,
                rules: options.rules ? options.rules : group.rules,
                account: this.account,
                pgpPrivateKey: this.decryptedPgpPvtKey,
                env: this.env,
            };
            const updateGroupConfigOptions = {
                chatId: spaceId,
                meta: options.meta ? options.meta : group.meta,
                scheduleAt: options.scheduleAt ? options.scheduleAt : group.scheduleAt,
                scheduleEnd: options.scheduleEnd
                    ? options.scheduleEnd
                    : group.scheduleEnd,
                status: options.status ? options.status : group.status,
                account: this.account,
                pgpPrivateKey: this.decryptedPgpPvtKey,
                env: this.env,
            };
            yield (0, updateGroupProfile_1.updateGroupProfile)(updateGroupProfileOptions);
            const groupDto = yield (0, updateGroupConfig_1.updateGroupConfig)(updateGroupConfigOptions);
            return (0, chat_1.groupInfoDtoToSpaceInfoDto)(groupDto);
        });
    }
    info(spaceId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const groupDto = yield PUSH_CHAT.getGroupInfo({
                chatId: spaceId,
                env: this.env,
            });
            return (0, chat_1.groupInfoDtoToSpaceInfoDto)(groupDto);
        });
    }
    permissions(spaceId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const getGroupAccessOptions = {
                chatId: spaceId,
                did: this.account,
                env: this.env,
            };
            return yield PUSH_CHAT.getGroupAccess(getGroupAccessOptions);
        });
    }
    add(spaceId, options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
            }
            const { role, accounts } = options;
            const validRoles = ['SPEAKER', 'LISTENER'];
            if (!validRoles.includes(role)) {
                throw new Error('Invalid role provided.');
            }
            if (!accounts || accounts.length === 0) {
                throw new Error('accounts array cannot be empty!');
            }
            accounts.forEach((account) => {
                if (!(0, helpers_1.isValidETHAddress)(account)) {
                    throw new Error(`Invalid account address: ${account}`);
                }
            });
            let response;
            if (role === 'SPEAKER') {
                response = yield PUSH_CHAT.addAdmins({
                    chatId: spaceId,
                    admins: accounts,
                    env: this.env,
                    account: this.account,
                    signer: this.signer,
                    pgpPrivateKey: this.decryptedPgpPvtKey,
                    overrideSecretKeyGeneration: false,
                });
            }
            else {
                response = yield PUSH_CHAT.addMembers({
                    chatId: spaceId,
                    members: accounts,
                    env: this.env,
                    account: this.account,
                    signer: this.signer,
                    pgpPrivateKey: this.decryptedPgpPvtKey,
                    overrideSecretKeyGeneration: false,
                });
            }
            return (0, chat_1.groupInfoDtoToSpaceInfoDto)(response);
        });
    }
    remove(spaceId, options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { accounts } = options;
            if (!this.signer) {
                throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
            }
            if (!accounts || accounts.length === 0) {
                throw new Error('Accounts array cannot be empty!');
            }
            accounts.forEach((account) => {
                if (!(0, helpers_1.isValidETHAddress)(account)) {
                    throw new Error(`Invalid account address: ${account}`);
                }
            });
            const adminsToRemove = [];
            const membersToRemove = [];
            for (const account of accounts) {
                const status = yield PUSH_CHAT.getGroupMemberStatus({
                    chatId: spaceId,
                    did: account,
                    env: this.env,
                });
                if (status.isAdmin) {
                    adminsToRemove.push(account);
                }
                else if (status.isMember) {
                    membersToRemove.push(account);
                }
            }
            if (adminsToRemove.length > 0) {
                yield PUSH_CHAT.removeAdmins({
                    chatId: spaceId,
                    admins: adminsToRemove,
                    env: this.env,
                    account: this.account,
                    signer: this.signer,
                    pgpPrivateKey: this.decryptedPgpPvtKey,
                    overrideSecretKeyGeneration: false,
                });
            }
            if (membersToRemove.length > 0) {
                yield PUSH_CHAT.removeMembers({
                    chatId: spaceId,
                    members: membersToRemove,
                    env: this.env,
                    account: this.account,
                    signer: this.signer,
                    pgpPrivateKey: this.decryptedPgpPvtKey,
                    overrideSecretKeyGeneration: false,
                });
            }
            return yield this.info(spaceId);
        });
    }
    modify(spaceId, options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { role, accounts } = options;
            if (!this.signer) {
                throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
            }
            const validRoles = ['SPEAKER', 'LISTENER'];
            if (!validRoles.includes(role)) {
                throw new Error('Invalid role provided.');
            }
            if (!accounts || accounts.length === 0) {
                throw new Error('accounts array cannot be empty!');
            }
            accounts.forEach((account) => {
                if (!(0, helpers_1.isValidETHAddress)(account)) {
                    throw new Error(`Invalid account address: ${account}`);
                }
            });
            let newRole = null;
            if (role === 'SPEAKER') {
                newRole = 'ADMIN';
            }
            else {
                newRole = 'MEMBER';
            }
            const response = yield PUSH_CHAT.modifyRoles({
                chatId: spaceId,
                newRole: newRole,
                members: accounts,
                env: this.env,
                account: this.account,
                signer: this.signer,
                pgpPrivateKey: this.decryptedPgpPvtKey,
                overrideSecretKeyGeneration: false,
            });
            return (0, chat_1.groupInfoDtoToSpaceInfoDto)(response);
        });
    }
    join(spaceId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
            }
            const status = yield PUSH_CHAT.getGroupMemberStatus({
                chatId: spaceId,
                did: this.account,
                env: this.env,
            });
            if (status.isPending) {
                yield PUSH_CHAT.approve({
                    senderAddress: spaceId,
                    env: this.env,
                    account: this.account,
                    signer: this.signer,
                    pgpPrivateKey: this.decryptedPgpPvtKey,
                    overrideSecretKeyGeneration: false,
                });
            }
            else if (!status.isMember) {
                yield PUSH_CHAT.addMembers({
                    chatId: spaceId,
                    members: [this.account],
                    env: this.env,
                    account: this.account,
                    signer: this.signer,
                    pgpPrivateKey: this.decryptedPgpPvtKey,
                    overrideSecretKeyGeneration: false,
                });
            }
            return yield this.info(spaceId);
        });
    }
    leave(spaceId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
            }
            const status = yield PUSH_CHAT.getGroupMemberStatus({
                chatId: spaceId,
                did: this.account,
                env: this.env,
            });
            let response;
            if (status.isAdmin) {
                response = yield PUSH_CHAT.removeAdmins({
                    chatId: spaceId,
                    admins: [this.account],
                    env: this.env,
                    account: this.account,
                    signer: this.signer,
                    pgpPrivateKey: this.decryptedPgpPvtKey,
                    overrideSecretKeyGeneration: false,
                });
            }
            else {
                response = yield PUSH_CHAT.removeMembers({
                    chatId: spaceId,
                    members: [this.account],
                    env: this.env,
                    account: this.account,
                    signer: this.signer,
                    pgpPrivateKey: this.decryptedPgpPvtKey,
                    overrideSecretKeyGeneration: false,
                });
            }
            return (0, chat_1.groupInfoDtoToSpaceInfoDto)(response);
        });
    }
    search(term, options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { page = 1, limit = 20 } = options !== null && options !== void 0 ? options : {};
            const response = yield PUSH_SPACE.search({
                searchTerm: term,
                pageNumber: page,
                pageSize: limit,
                env: this.env,
            });
            return response.map((space) => PUSH_CHAT.spaceDtoToSpaceInfoDto(space));
        });
    }
    trending(options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { page = 1, limit = 20 } = options !== null && options !== void 0 ? options : {};
            const response = yield PUSH_SPACE.trending({
                page: page,
                limit: limit,
                env: this.env,
            });
            return response;
        });
    }
    list(type, options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const accountToUse = (options === null || options === void 0 ? void 0 : options.overrideAccount) || this.account;
            const listParams = {
                account: accountToUse,
                pgpPrivateKey: this.decryptedPgpPvtKey,
                page: options === null || options === void 0 ? void 0 : options.page,
                limit: options === null || options === void 0 ? void 0 : options.limit,
                env: this.env,
                toDecrypt: !!this.signer, // Set to false if signer is undefined or null,
            };
            switch (type) {
                case pushAPITypes_1.SpaceListType.SPACES:
                    return yield PUSH_SPACE.spaces(listParams);
                case pushAPITypes_1.SpaceListType.REQUESTS:
                    return yield PUSH_SPACE.requests(listParams);
                default:
                    throw new Error('Invalid Space List Type');
            }
        });
    }
    accept(spaceId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
            }
            return this.chatInstance.accept(spaceId);
        });
    }
    reject(spaceId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
            }
            return this.chatInstance.reject(spaceId);
        });
    }
    get chat() {
        return {
            send: (recipient, options) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                return this.chatInstance.send(recipient, options);
            }),
            decrypt: (messages) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                if (!this.signer) {
                    throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
                }
                return yield this.chatInstance.decrypt(messages);
            }),
            latest: (target) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                return yield this.chatInstance.latest(target);
            }),
            history: (target, options) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                return yield this.chatInstance.history(target, options);
            }),
        };
    }
    initialize(options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { onChange, spaceId } = options;
            if (!this.signer) {
                throw new Error('Signer is required for push space');
            }
            if (!this.decryptedPgpPvtKey) {
                throw new Error('PushSDK was initialized in readonly mode. Space functionality is not available.');
            }
            const chainId = yield new helpers_2.Signer(this.signer).getChainId();
            if (!chainId) {
                throw new Error('Chain Id not retrievable from signer');
            }
            // Initialize the spacev1 instance with the provided options
            const spaceV1Instance = new Space_1.Space({
                signer: this.signer,
                chainId,
                pgpPrivateKey: this.decryptedPgpPvtKey,
                setSpaceData: onChange,
                address: this.account,
                env: this.env,
            });
            // Call the space v1 initialize() method to populate the space data
            yield spaceV1Instance.initialize({ spaceId });
            const spaceInfo = yield this.info(spaceId);
            // Return an instance of the space v2 class
            return new SpaceV2_1.SpaceV2({
                spaceV1Instance,
                spaceInfo,
            });
        });
    }
}
exports.Space = Space;
//# sourceMappingURL=space.js.map