"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const http_1 = require("http");
const logger_1 = require("../lib/logger");
const websocket_1 = require("websocket");
/**
 *
 */
class TelloTelemetry {
    constructor() {
        this.wsClients = [];
        this.webSocketsServerPort = 1338;
    }
    /**
     *
     * @return {Promise<TelloTelemetry>}
     */
    start() {
        return new Promise(resolve => {
            this.timer = new Date().getTime();
            this.httpServer = http_1.createServer(() => {
            });
            this.httpServer.listen(this.webSocketsServerPort, () => {
                logger_1.Logger.info('[TelloTelemetry - WS]', 'Server is listening on port', this.webSocketsServerPort);
                resolve(this);
            });
            this.wsServer = new websocket_1.server({
                httpServer: this.httpServer
            });
            // WebSocket server
            this.wsServer.on('request', (request) => {
                const cnx = request.accept(null, request.origin);
                logger_1.Logger.info('[TelloTelemetry - WS]', 'Connection from origin', request.origin);
                const index = this.wsClients.push(cnx) - 1;
                logger_1.Logger.info('[TelloTelemetry - WS]', 'Connection accepted.');
                cnx.on('close', () => {
                    logger_1.Logger.info('[TelloTelemetry - WS]', 'Peer', cnx.remoteAddress, 'disconnected');
                    this.wsClients.splice(index, 1);
                });
            });
        });
    }
    /**
     *
     * @param {OSDData} data
     */
    send(data) {
        this.sendBatch(JSON.stringify(data));
    }
    /**
     *
     * @param chunk
     */
    sendVideo(chunk) {
        this.wsClients.forEach(c => c.send(chunk));
    }
    stop() {
        return new Promise(resolve => {
            this.httpServer.close(() => {
                logger_1.Logger.info('[TelloTelemetry - WS]', 'Web Server stopped');
                resolve(this);
            });
        });
    }
    /**
     *
     * @param {string} data
     */
    sendBatch(data) {
        if (new Date().getTime() - this.timer >= 500) {
            this.wsClients.forEach(c => c.sendUTF(data));
            this.timer = new Date().getTime();
        }
    }
}
exports.TelloTelemetry = TelloTelemetry;
//# sourceMappingURL=telemetry.js.map