"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutojoinUpgradedRoomsMixin = void 0;
/**
 * Automatically tries to join upgraded rooms
 * @category Mixins
 */
class AutojoinUpgradedRoomsMixin {
    static setupOnClient(client) {
        client.on("room.archived", (roomId, tombstoneEvent) => {
            if (!tombstoneEvent['content'])
                return;
            if (!tombstoneEvent['sender'])
                return;
            if (!tombstoneEvent['content']['replacement_room'])
                return;
            const serverName = tombstoneEvent['sender'].split(':').splice(1).join(':');
            return client.joinRoom(tombstoneEvent['content']['replacement_room'], [serverName]);
        });
    }
    static setupOnAppservice(appservice) {
        appservice.on("room.archived", (roomId, tombstoneEvent) => __awaiter(this, void 0, void 0, function* () {
            if (!tombstoneEvent['content'])
                return;
            if (!tombstoneEvent['sender'])
                return;
            if (!tombstoneEvent['content']['replacement_room'])
                return;
            const newRoomId = tombstoneEvent['content']['replacement_room'];
            const serverName = tombstoneEvent['sender'].split(':').splice(1).join(':');
            const botClient = appservice.botIntent.underlyingClient;
            yield botClient.joinRoom(newRoomId, [serverName]);
            const userIds = yield botClient.getJoinedRoomMembers(roomId);
            const joinUserIds = userIds.filter(u => u !== appservice.botUserId && appservice.isNamespacedUser(u));
            return yield Promise.all(joinUserIds.map(u => appservice.getIntentForUserId(u).joinRoom(newRoomId)));
        }));
    }
}
exports.AutojoinUpgradedRoomsMixin = AutojoinUpgradedRoomsMixin;
