"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const WS = __importStar(require("ws"));
const Http = __importStar(require("http"));
const UrlEncode = __importStar(require("urlencode"));
const Utils = __importStar(require("../../util/src"));
const QRCode = require('qrcode-terminal');
var Singleton;
(function (Singleton) {
    Singleton.IP = Utils.Net.localIP();
    Singleton.PORT = 9001;
    Singleton.server = Http.createServer();
    Singleton.wss = new WS.Server({ server: Singleton.server });
    Singleton.receiveSocketMessage = undefined;
})(Singleton = exports.Singleton || (exports.Singleton = {}));
Singleton.wss.on('error', error => {
    Utils.Console.error(`${error}`);
});
Singleton.wss.on('pong', e => {
});
Singleton.wss.on('listening', () => {
    Utils.Console.info(`通信通道已就绪，请扫描二维码或输入端口号进行连接`);
    QRCode.generate(qrvalue(), { small: true }, (value) => {
        Utils.Console.info(`\n${value}`);
    });
});
Singleton.wss.on('connection', (client, request) => {
    var _a;
    if (request.headers.session) {
        //  client 挂载 session
        const _client = client;
        _client.session = JSON.parse(decodeURI(typeof request.headers.session === 'string' ? request.headers.session : '{}'));
        Utils.Console.info(`${(_a = _client === null || _client === void 0 ? void 0 : _client.session) === null || _a === void 0 ? void 0 : _a.name} 已连接`);
    }
    else {
        Utils.Console.info(`cube-devtools 已连接`);
    }
    client.on('error', (e) => {
        client.terminate();
    });
    client.on('close', (e) => {
        client.terminate();
        Utils.Console.warn(`${client.session ? client.session.name : 'cube-devtools'} 失去连接`);
    });
    client.on('pong', () => {
    });
    client.on('message', (data) => {
        Utils.Console.info(`${data}`);
        if (Singleton.receiveSocketMessage) {
            Singleton.receiveSocketMessage(data, client);
        }
    });
});
setInterval(() => {
    if (Singleton.wss && Singleton.wss.clients) {
        for (const client of Singleton.wss.clients) {
            if (client.readyState === WS.CLOSED) {
                client.terminate();
            }
        }
    }
}, 10000);
function launch() {
    return __awaiter(this, void 0, void 0, function* () {
        Utils.Console.info(`清理端口 [${Singleton.PORT}]`);
        yield Utils.Net.cleanPort(Singleton.PORT);
        Utils.Console.info(`启动服务 [${Singleton.IP}:${Singleton.PORT}]`);
        return new Promise((resolve, reject) => {
            Singleton.server.listen(Singleton.PORT, () => {
                resolve();
            });
        });
    });
}
exports.launch = launch;
function clientSessions() {
    const sessions = new Array();
    if (Singleton.wss && Singleton.wss.clients) {
        for (const aclient of Singleton.wss.clients) {
            const _aclient = aclient;
            if (aclient.readyState === WS.OPEN && _aclient.session) {
                sessions.push(_aclient.session);
            }
        }
    }
    return sessions;
}
exports.clientSessions = clientSessions;
function broadcase(data) {
    if (Singleton.wss) {
        for (const client of Singleton.wss.clients) {
            const _client = client;
            if (client.readyState === WS.OPEN && _client.session) {
                client.send(data);
            }
        }
    }
    return Promise.resolve();
}
exports.broadcase = broadcase;
function send(token, data) {
    return new Promise((resolve, reject) => {
        const cli = client(token);
        if (cli) {
            cli.send(data, error => {
                if (error) {
                    reject(error);
                }
                else {
                    resolve();
                }
            });
        }
        else {
            reject(Error(`当前没有已连接的设备`));
        }
    });
}
exports.send = send;
function client(token) {
    let client = undefined;
    if (Singleton.wss && Singleton.wss.clients) {
        for (const aclient of Singleton.wss.clients) {
            const _aclient = aclient;
            if (aclient.readyState === WS.OPEN && _aclient.session.token === token) {
                client = aclient;
            }
        }
    }
    return client;
}
function qrvalue() {
    return `alipays://platformapi/startApp?appId=20002042&action=connect&ip=${Singleton.IP}&port=${Singleton.PORT}`;
}
exports.qrvalue = qrvalue;
function fillFileRemoteUrl(filePath) {
    return `http://${Singleton.IP}:${Singleton.PORT}/api?action=file&path=${UrlEncode.encode(filePath)}&stamp=${(new Date()).getTime()}`;
}
exports.fillFileRemoteUrl = fillFileRemoteUrl;
//# sourceMappingURL=server.js.map