const kcp = require('./build/Release/kcp')
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
/**
 * @params ID 通信id: 110
 * @pramss port 端口默认: 41234
 * @params type 工作模式: 急速1 |  默认普通0 
 */
class KcpServer {
    constructor(ID = 110, port = 41234, type = 0) {
        this.ID = ID
        this.port = port
        this.type = type
        this.clients = {}
        this.timer = null
        this.output = (data, size, context) => server.send(data, 0, size, context.port, context.address)
        this.Init()
    }


    // init
    Init() {
        server.bind(this.port);

        server.on('listening', () => {
            console.log(66,JSON.stringify(server));
            const address = server.address();
            console.log(`server listening ${address.address} : ${address.port}`);
            const time = this.type ? 10 : 50
            this.timer = setInterval(() => {
                for (const k in this.clients) {
                    const kcpobj = this.clients[k];
                    kcpobj.update(Date.now());
                    const recv = kcpobj.recv();
                    if (recv) {
                        console.log(`server recv ${recv} from ${kcpobj.context().address}:${kcpobj.context().port}`);
                        kcpobj.send('RE-' + recv);
                    }
                }                
            }, time);
        })


        server.on('message', (msg, rinfo) => {
            const k = rinfo.address + '_' + rinfo.port;
            if (undefined === this.clients[k]) {
                const context = {
                    address: rinfo.address,
                    port: rinfo.port
                };
                this.clients[k] = new kcp.KCP(this.ID, context);
                if(this.type){
                    this.clients[k].nodelay(1, 10, 2, 1);

                }else{
                    this.clients[k].nodelay(0, 50, 0, 0);
                }
                this.clients[k].output(this.output);
            }
            this.clients[k].input(msg);
        })

        server.on('error', er => {
            clearInterval(this.timer)
            this.clients = {}
            this.timer = null
        })
    }
}

new KcpServer()
