/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { strict as assert } from "node:assert";
import * as fs from "node:fs";
import { createGroupOp } from "../opBuilder.js";
import { MergeTreeDeltaType } from "../ops.js";
import { replayResultsPath } from "./mergeTreeOperationRunner.js";
import { TestClient } from "./testClient.js";
import { TestClientLogger } from "./testClientLogger.js";
describe("MergeTree.Client", () => {
    for (const filePath of fs.readdirSync(replayResultsPath)) {
        it(`Replay ${filePath}`, async () => {
            const file = JSON.parse(fs.readFileSync(`${replayResultsPath}/${filePath}`).toString());
            const msgClients = new Map();
            const originalClient = new TestClient({ mergeTreeEnableObliterate: true });
            msgClients.set("A", { client: originalClient, msgs: [] });
            originalClient.insertTextLocal(0, file[0].initialText);
            originalClient.startOrUpdateCollaboration("A");
            for (const group of file) {
                for (const msg of group.msgs) {
                    assert(msg.clientId, "expected clientId to be defined");
                    if (!msgClients.has(msg.clientId)) {
                        const client = await TestClient.createFromClientSnapshot(originalClient, msg.clientId);
                        msgClients.set(msg.clientId, { client, msgs: [] });
                    }
                }
            }
            for (const group of file) {
                const logger = new TestClientLogger([...msgClients.values()].map((mc) => mc.client));
                const initialText = logger.validate();
                assert.strictEqual(initialText, group.initialText, "Initial text not as expected");
                for (const msg of group.msgs) {
                    const msgClient = msgClients.get(msg.clientId);
                    while (msgClient.msgs.length > 0 &&
                        msg.referenceSequenceNumber > msgClient.client.getCurrentSeq()) {
                        msgClient.client.applyMsg(msgClient.msgs.shift());
                    }
                    const op = msg.contents;
                    msgClient.client.localTransaction(op.type === MergeTreeDeltaType.GROUP ? op : createGroupOp(op));
                    for (const mc of msgClients)
                        mc[1].msgs.push(msg);
                }
                for (const mc of msgClients) {
                    while (mc[1].msgs.length > 0) {
                        mc[1].client.applyMsg(mc[1].msgs.shift());
                    }
                }
                const result = logger.validate();
                assert.strictEqual(result, group.resultText, "Result text not as expected");
                logger.dispose();
            }
        }).timeout(30 * 10000);
    }
});
//# sourceMappingURL=client.replay.spec.js.map