/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils";
import { assertIsStableId } from "@fluidframework/container-runtime";
import { brand, extractFromOpaque } from "../../util";
/**
 * Creates a {@link NodeKeyManager} from the given {@link IIdCompressor}.
 * @param idCompressor - the compressor to use for key generation, compression, and decompression.
 * If undefined, then attempts to generate or convert keys will throw an error.
 */
export function createNodeKeyManager(idCompressor) {
    return {
        generateLocalNodeKey: () => {
            assert(idCompressor !== undefined, 0x6e4 /* Runtime IdCompressor must be available to generate local node keys */);
            return brand(idCompressor.generateCompressedId());
        },
        localizeNodeKey: (key) => {
            assert(idCompressor !== undefined, 0x6e5 /* Runtime IdCompressor must be available to convert node keys */);
            return brand(idCompressor.recompress(key));
        },
        stabilizeNodeKey: (key) => {
            assert(idCompressor !== undefined, 0x6e6 /* Runtime IdCompressor must be available to convert node keys */);
            return brand(
            // TODO: The assert below is required for type safety but is maybe slow
            assertIsStableId(idCompressor.decompress(extractFromOpaque(key))));
        },
    };
}
/**
 * Create a {@link NodeKeyManager} that generates deterministic {@link StableNodeKey}s and {@link LocalNodeKey}s.
 * @remarks This is useful for test environments because it will always yield the same keys in the same order.
 * It should not be used for production environments for the same reason; the {@link StableNodeKey}s are not universally unique.
 */
export function createMockNodeKeyManager() {
    return new MockNodeKeyManager();
}
class MockNodeKeyManager {
    constructor() {
        this.count = 0;
    }
    generateStableNodeKey() {
        return brand(this.createMockStableId(this.count++));
    }
    generateLocalNodeKey() {
        return this.localizeNodeKey(this.generateStableNodeKey());
    }
    localizeNodeKey(key) {
        return brand(Number.parseInt(key.substring(30), 16));
    }
    stabilizeNodeKey(key) {
        return brand(this.createMockStableId(extractFromOpaque(key)));
    }
    createMockStableId(offset) {
        assert(offset >= 0, 0x6e7 /* UUID offset may not be negative */);
        assert(offset < 281474976710656, 0x6e8 /* UUID offset must be at most 16^12 */);
        return assertIsStableId(`a110ca7e-add1-4000-8000-${Math.round(offset).toString(16).padStart(12, "0")}`);
    }
}
//# sourceMappingURL=nodeKeyManager.js.map