"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GroupKeyQueue = void 0;
class GroupKeyQueue {
    currentGroupKey;
    queuedGroupKey; // a group key queued to be rotated into use after the call to useGroupKey
    streamId;
    authentication;
    groupKeyManager;
    static async createInstance(streamId, authentication, groupKeyManager) {
        const instance = new GroupKeyQueue(streamId, authentication, groupKeyManager);
        instance.currentGroupKey = await instance.groupKeyManager.fetchLatestEncryptionKey(await authentication.getAddress(), streamId);
        return instance;
    }
    constructor(streamId, authentication, groupKeyManager) {
        this.streamId = streamId;
        this.authentication = authentication;
        this.groupKeyManager = groupKeyManager;
    }
    async useGroupKey() {
        // Ensure we have a current key by picking a queued key or generating a new one
        if (!this.currentGroupKey) {
            this.currentGroupKey = this.queuedGroupKey || await this.rekey();
            this.queuedGroupKey = undefined;
        }
        // Always return an array consisting of currentGroupKey and queuedGroupKey (latter may be undefined)
        const result = {
            current: this.currentGroupKey,
            next: this.queuedGroupKey,
        };
        // Perform the rotate if there's a next key queued
        if (this.queuedGroupKey) {
            this.currentGroupKey = this.queuedGroupKey;
            this.queuedGroupKey = undefined;
        }
        return result;
    }
    async rotate(newKey) {
        const publisherId = await this.authentication.getAddress();
        newKey = await this.groupKeyManager.storeKey(newKey, publisherId, this.streamId);
        this.queuedGroupKey = newKey;
        return newKey;
    }
    async rekey(newKey) {
        const publisherId = await this.authentication.getAddress();
        newKey = await this.groupKeyManager.storeKey(newKey, publisherId, this.streamId);
        this.currentGroupKey = newKey;
        this.queuedGroupKey = undefined;
        return newKey;
    }
}
exports.GroupKeyQueue = GroupKeyQueue;
//# sourceMappingURL=GroupKeyQueue.js.map