"use strict";
// Copyright 2019 - 2021 The Matrix.org Foundation C.I.C.
// Copyright 2022 - 2024 Gnuxie <Gnuxie@protonmail.com>
//
// SPDX-License-Identifier: Apache-2.0
//
// SPDX-FileAttributionText: <text>
// This modified file incorporates work from mjolnir
// https://github.com/matrix-org/mjolnir
// </text>
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProtectroomsOnInvite = void 0;
const matrix_protection_suite_1 = require("matrix-protection-suite");
const mps_interface_adaptor_1 = require("@the-draupnir-project/mps-interface-adaptor");
const typebox_1 = require("@sinclair/typebox");
const interface_manager_1 = require("@the-draupnir-project/interface-manager");
const log = new matrix_protection_suite_1.Logger("ProtectRoomsOnInvite");
const PROTECT_ROOMS_ON_INVITE_PROMPT_LISTENER = "me.marewolf.draupnir.protect_rooms_on_invite";
// would be nice to be able to use presentation types here idk.
const ProtectRoomsOnInvitePromptContext = typebox_1.Type.Object({
    invited_room: matrix_protection_suite_1.RoomIDPermalinkSchema,
});
class ProtectroomsOnInvite {
    draupnir;
    protectedRoomsSet;
    protectPromptListener = this.protectListener.bind(this);
    constructor(draupnir, protectedRoomsSet) {
        this.draupnir = draupnir;
        this.protectedRoomsSet = protectedRoomsSet;
        this.draupnir.reactionHandler.on(PROTECT_ROOMS_ON_INVITE_PROMPT_LISTENER, this.protectPromptListener);
    }
    handleProtectionDisable() {
        this.draupnir.reactionHandler.off(PROTECT_ROOMS_ON_INVITE_PROMPT_LISTENER, this.protectPromptListener);
    }
    promptToProtect(candidateRoom, invitation) {
        void (0, matrix_protection_suite_1.Task)((async () => {
            const renderPromptProtect = () => (interface_manager_1.DeadDocumentJSX.JSXFactory("root", null,
                (0, mps_interface_adaptor_1.renderMentionPill)(invitation.sender, invitation.sender),
                " has invited me to  ",
                (0, mps_interface_adaptor_1.renderRoomPill)(candidateRoom),
                ", would you like to protect this room?"));
            const reactionMap = new Map(Object.entries({ OK: "OK", Cancel: "Cancel" }));
            const promptSendResult = await (0, mps_interface_adaptor_1.sendMatrixEventsFromDeadDocument)(this.draupnir.clientPlatform.toRoomMessageSender(), this.draupnir.managementRoomID, renderPromptProtect(), {
                additionalContent: this.draupnir.reactionHandler.createAnnotation(PROTECT_ROOMS_ON_INVITE_PROMPT_LISTENER, reactionMap, {
                    invited_room: candidateRoom.toPermalink(),
                }),
            });
            if ((0, matrix_protection_suite_1.isError)(promptSendResult)) {
                log.error(`Could not send the prompt to protect the room: ${candidateRoom.toPermalink()}`, promptSendResult.error);
                return;
            }
            const promptEventID = promptSendResult.ok.at(0);
            if (promptEventID === undefined) {
                throw new TypeError(`We should have an eventID for the event that we just sent...`);
            }
            await this.draupnir.reactionHandler.addReactionsToEvent(this.draupnir.managementRoomID, promptEventID, reactionMap);
            return (0, matrix_protection_suite_1.Ok)(undefined);
        })());
    }
    protectListener(key, _item, rawContext, _reactionMap, promptEvent) {
        if (key === "Cancel") {
            void (0, matrix_protection_suite_1.Task)(this.draupnir.reactionHandler.cancelPrompt(promptEvent));
            return;
        }
        if (key !== "OK") {
            return;
        }
        const context = matrix_protection_suite_1.Value.Decode(ProtectRoomsOnInvitePromptContext, rawContext);
        if ((0, matrix_protection_suite_1.isError)(context)) {
            log.error(`Could not decode context from prompt event`, context.error);
            (0, mps_interface_adaptor_1.renderActionResultToEvent)(this.draupnir.clientPlatform.toRoomMessageSender(), this.draupnir.clientPlatform.toRoomReactionSender(), promptEvent, context);
            return;
        }
        void (0, matrix_protection_suite_1.Task)((async () => {
            const resolvedRoom = await this.draupnir.clientPlatform
                .toRoomResolver()
                .resolveRoom(context.ok.invited_room);
            if ((0, matrix_protection_suite_1.isError)(resolvedRoom)) {
                resolvedRoom.elaborate(`Could not resolve the room to protect from the MatrixRoomReference: ${context.ok.invited_room.toPermalink()}.`);
                (0, mps_interface_adaptor_1.renderActionResultToEvent)(this.draupnir.clientPlatform.toRoomMessageSender(), this.draupnir.clientPlatform.toRoomReactionSender(), promptEvent, resolvedRoom);
                return;
            }
            const addResult = await this.protectedRoomsSet.protectedRoomsManager.addRoom(resolvedRoom.ok);
            if ((0, matrix_protection_suite_1.isError)(addResult)) {
                addResult.elaborate(`Could not protect the room: ${resolvedRoom.ok.toPermalink()}`);
                (0, mps_interface_adaptor_1.renderActionResultToEvent)(this.draupnir.clientPlatform.toRoomMessageSender(), this.draupnir.clientPlatform.toRoomReactionSender(), promptEvent, addResult);
                return;
            }
            (0, mps_interface_adaptor_1.renderActionResultToEvent)(this.draupnir.clientPlatform.toRoomMessageSender(), this.draupnir.clientPlatform.toRoomReactionSender(), promptEvent, addResult);
            void (0, matrix_protection_suite_1.Task)(this.draupnir.reactionHandler.completePrompt(promptEvent.room_id, promptEvent.event_id));
        })());
    }
}
exports.ProtectroomsOnInvite = ProtectroomsOnInvite;
//# sourceMappingURL=ProtectRoomsOnInvite.js.map