import { logger } from '@crosslab/service-common';
import Queue from 'queue';
import { sendSignalingMessage } from '../signaling.js';
export class SignalingQueue {
    deviceUrl;
    peerconnectionUrl;
    queue;
    _state = 'new';
    closedPromise;
    onClose;
    constructor(peerconnectionUrl, deviceUrl) {
        this.deviceUrl = deviceUrl;
        this.peerconnectionUrl = peerconnectionUrl;
        this.queue = new Queue({
            concurrency: 1,
        });
        let closedPromiseResolve;
        this.closedPromise = new Promise(resolve => {
            closedPromiseResolve = resolve;
        });
        this.onClose = () => {
            this.queue.end();
            closedPromiseResolve();
        };
    }
    get state() {
        return this._state;
    }
    add(signalingMessage) {
        this.queue.push(async () => {
            await this.sendSignalingMessage(signalingMessage);
            if (signalingMessage.messageType === 'command') {
                switch (signalingMessage.command) {
                    case 'closePeerconnection':
                        this._state = 'closed';
                        this.onClose();
                        break;
                }
            }
        });
        if (this.state === 'started')
            this.start();
    }
    async sendSignalingMessage(signalingMessage) {
        try {
            await sendSignalingMessage(this.deviceUrl, signalingMessage, this.peerconnectionUrl);
        }
        catch (error) {
            logger.log('error', 'An error occurred while trying to send a signaling message', {
                data: {
                    error,
                    errorMessage: error instanceof Error ? error.message : undefined,
                    message: signalingMessage,
                    targetDevice: this.deviceUrl,
                    peerconnection: this.peerconnectionUrl,
                },
            });
        }
    }
    start() {
        this.queue.start(error => {
            if (error)
                logger.log('error', 'An error occurred while processing a signaling message', {
                    data: {
                        error,
                        targetDevice: this.deviceUrl,
                        peerconnection: this.peerconnectionUrl,
                    },
                });
        });
        if (this._state != 'closed')
            this._state = 'started';
    }
    stop() {
        this.queue.stop();
        if (this._state != 'closed')
            this._state = 'stopped';
    }
    async close() {
        if (this.state !== 'new' && this.state !== 'closed')
            this.add({
                messageType: 'command',
                command: 'closePeerconnection',
                connectionUrl: this.peerconnectionUrl,
            });
        else if (this.state === 'new')
            this.onClose();
        return this.closedPromise;
    }
}
//# sourceMappingURL=signalingQueue.js.map