"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const WebSocket = require("ws");
const DEBUG = require("debug");
const debug = DEBUG('weex:preview');
class HotReloadServer {
    constructor(options) {
        this.clients = [];
        this.wss = this.startWebSocket(options);
    }
    startWebSocket(options) {
        const wss = new WebSocket.Server(options);
        wss.on('connection', ws => {
            this.clients.push(ws);
            ws.on('message', message => {
                this.clients.forEach(client => {
                    if (client.readyState === WebSocket.OPEN) {
                        client.send('websocket connected', err => {
                            if (err) {
                                debug(err);
                            }
                        });
                    }
                });
            });
            // while socket recive close or error sigle, socket destroy and remve client from clients
            // websocket close handle
            ws.on('close', data => {
                debug('websocket close -> ', data);
                if (ws && ws.upgradeReq) {
                    this.clients.splice(this.findClient(ws.upgradeReq.url));
                }
                ws._socket.destroy();
                ws.close();
            });
            // websocket error handle
            ws.on('error', error => {
                if (error) {
                    debug('websocket error -> ', error);
                    if (ws && ws.upgradeReq) {
                        this.clients.splice(this.findClient(ws.upgradeReq.url), 1);
                    }
                    ws._socket.destroy();
                    ws.close();
                }
            });
        });
        return wss;
    }
    // send web socket messsage to client
    async sendSocketMessage(message) {
        return new Promise((resolve, reject) => {
            this.clients.forEach(client => {
                if (client.readyState === WebSocket.OPEN) {
                    client.send(message || 'refresh', (err) => {
                        if (err) {
                            debug('sending websocket message error -> ', err);
                            reject(err);
                        }
                        else {
                            resolve('success');
                        }
                    });
                }
            });
        });
    }
    // find client through request url
    findClient(url) {
        for (let i = 0; i < this.clients.length; i++) {
            if (this.clients[i].upgradeReq.url === url) {
                return i;
            }
        }
        return null;
    }
}
exports.HotReloadServer = HotReloadServer;
exports.default = HotReloadServer;
//# sourceMappingURL=HotReloadServer.js.map