const net = require('net')
let ServerArr = [];
let IPBlacklist = [];
var player = [];
var idObj = {};
exports.InsertIPBlacklist = function (ip) {
    IPBlacklist[IPBlacklist.length] = ip;
}
exports.NewServer = function (ServerData, MsgFun = undefined) {
    ServerArr[ServerArr.length] = null;
    let IntServer = ServerArr.length - 1;
    idObj[IntServer] = {};
    ServerArr[IntServer] = net.createServer((socket) => {
        socket.on('data', (dt) => {
            for (let index = 0; index < IPBlacklist.length; index++) {
                let IPStr = IPBlacklist[index];
                if (IPStr == undefined) {
                    continue;
                }
                if (socket.remoteFamily != undefined) {
                    if (socket.remoteFamily == IPStr) {
                        socket.destroy()
                    }
                }
                if (socket.remoteAddress != undefined) {
                    if (socket.remoteAddress == IPStr) {
                        socket.destroy()
                    }
                }
            }
            if (MsgFun != undefined) {
                let RetData = MsgFun({
                    "状态": "收到数据",
                    "本地端口地址": socket.localPort,
                    "本地IP地址": socket.localAddress,
                    "进程端口地址": socket.remotePort,
                    "进程IP协议": socket.remoteFamily,
                    "进程IP地址": socket.remoteAddress,
                    "数据内容": dt,
                    "id": socket.socketIdxos,
                    "接收长度": socket.bytesRead
                })
                if (RetData == undefined) {
                    RetData = {}
                }
                try {
                    if (RetData["是否反馈"] != undefined) {
                        if (RetData["是否反馈"] == true) {
                            if (RetData["反馈数据"] != "") {
                                socket.write(RetData["反馈数据"]);
                            }
                        }
                    }
                    if (RetData["是否断开"] != undefined) {
                        if (RetData["是否断开"] == true) {
                            socket.destroy()
                        }
                    }
                } catch (err) {

                }
            }
        })
        socket.on('close', (dt) => {
            ServerArr[IntServer].getConnections(function (err, count) {
                try {
                    delete idObj[IntServer][socket.socketIdxos]
                } catch (error) {
                    
                }
                if (MsgFun != undefined) {
                    MsgFun({
                        "状态": "客户下线",
                        "连接总量": count,
                        "本地端口地址": socket.localPort,
                        "本地IP地址": socket.localAddress,
                        "进程端口地址": socket.remotePort,
                        "进程IP协议": socket.remoteFamily,
                        "id": socket.socketIdxos,
                        "进程IP地址": socket.remoteAddress
                    })
                }
            });
        })
        socket.on('end', (dt) => {
            let RetData = MsgFun({
                "状态": "任务完毕",
                "本地端口地址": socket.localPort,
                "本地IP地址": socket.localAddress,
                "进程端口地址": socket.remotePort,
                "进程IP协议": socket.remoteFamily,
                "id": socket.socketIdxos,
                "进程IP地址": socket.remoteAddress
            })
            if (RetData == undefined) {
                RetData = {}
            }
            try {
                if (RetData["是否反馈"] != undefined) {
                    if (RetData["是否反馈"] == true) {
                        if (RetData["反馈数据"] != "") {
                            socket.write(RetData["反馈数据"]);
                        }
                    }
                }
                if (RetData["是否断开"] != undefined) {
                    if (RetData["是否断开"] == true) {
                        socket.destroy()
                    }
                }
            } catch (err) {

            }
        })

    })
    if (ServerData["端口"] == undefined) {
        ServerData["端口"] = 3000
    }
    if (ServerData["地址"] == undefined) {
        ServerData["地址"] = "0.0.0.0"
    }
    if (ServerData["最大连接数"] == undefined) {
        ServerData["最大连接数"] = 1000;
    }
    ServerArr[IntServer].listen(ServerData["端口"], ServerData["地址"], () => {
        ServerArr[IntServer].maxConnections = ServerData["最大连接数"];
        if (MsgFun != undefined) {
            MsgFun({ "状态": "启动服务成功" })
        }
    })
    ServerArr[IntServer].on('connection', socket => {
        //7.获取客户度接入的数量：
        ServerArr[IntServer].getConnections(function (err, count) {
            let socketIdxos = player.length + 1;
            player[player.length] = socketIdxos
            socket.socketIdxos = socketIdxos
            idObj[IntServer][socketIdxos] = socket;
            if (MsgFun != undefined) {
                let RetData = MsgFun({
                    "状态": "新的接入",
                    "连接总量": count,
                    "本地端口地址": socket.localPort,
                    "本地IP地址": socket.localAddress,
                    "进程端口地址": socket.remotePort,
                    "远程IP协议": socket.remoteFamily,
                    "id": socket.socketIdxos,
                    "进程IP地址": socket.remoteAddress
                })
                if (RetData == undefined) {
                    RetData = {}
                }
                if (RetData["是否反馈"] != undefined) {
                    if (RetData["是否反馈"] == true) {
                        if (RetData["反馈数据"] != "") {
                            socket.write(RetData["反馈数据"]);
                        }
                    }
                }
                if (RetData["是否断开"] != undefined) {
                    if (RetData["是否断开"] == true) {
                        socket.destroy()
                    }
                }
            }
        });
        if (ServerData["是否组包"] == undefined) {
            ServerData["是否组包"] = false
        }
        if (ServerData["是否组包"] == true) {
            socket.setNoDelay(true);
        }
    })
    ServerArr[IntServer].on('close', () => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "服务器关闭" })
        }
    })
    ServerArr[IntServer].on('drop', () => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "连接到达上限" })
        }
    })
    ServerArr[IntServer].on('error', () => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "服务发生错误" })
        }
    })
    return IntServer;
}
exports.ServerClose = function (server) {
    if (server == undefined) {
        return;
    }
    try {
        let keys = Object.keys(idObj[server]); 
        for (let index = 0; index < keys.length; index++) {
            idObj[server][keys[index]].destroy()
        } 
    } catch (error) {
        
    }
    ServerArr[server].close(() => {
        try {
            idObj[server] = {};
        } catch (error) {
            
        }
    });
}
exports.socketList = function (ServerIDInt) {
    let retdata = [];
    if (idObj[ServerIDInt]) {
        for (let key in idObj[ServerIDInt]) {
            retdata[retdata.length] = key;
        }
        return retdata;
    }
    return [];
}
exports.send = function (ServerIDInt, id, data) {
    if (idObj[ServerIDInt]) {
        if (idObj[ServerIDInt][id]) {
            idObj[ServerIDInt][id].write(data)
        }
    }
}
exports.Disconnect = function (ServerIDInt, id) {
    if (idObj[ServerIDInt]) {
        if (idObj[ServerIDInt][id]) {
            idObj[ServerIDInt][id].destroy()
        }
    }
}


exports.NewSocket = function (ServerData, MsgFun = undefined) {
    if (ServerData["端口"] == undefined) {
        ServerData["端口"] = 3000
    }
    if (ServerData["地址"] == undefined) {
        ServerData["地址"] = "127.0.0.1"
    }
    ServerArr[ServerArr.length] = null;
    let IntServer = ServerArr.length - 1;
    //2.创建tcp客户端：net.Socket(obj)中可以传入一个obj对象，其属性分别为：fd文件描述、readable是否允许可读、writeable是否可写、allowHalfOpen:false时，tcp服务器接收到客户端发送的fin包后会回发，为true时不回发，前三个属性的默认值为false
    ServerArr[IntServer] = new net.Socket()
    //3.连接tcp服务器：
    ServerArr[IntServer].connect(ServerData["端口"], ServerData["地址"], () => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "连接服务成功" })
        }
    })
    ServerArr[IntServer].on('data', (dt) => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "收到数据", "数据内容": dt })
        }
    })
    ServerArr[IntServer].on('end', () => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "任务完毕" })
        }
    })
    ServerArr[IntServer].on('error', (Error) => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "发现客户端错误", "错误信息": Error })
        }
    })
    ServerArr[IntServer].on('close', () => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "客户端被关闭" })
        }
    })

    return IntServer;
}
exports.SocketWrite = function (IntServer, Data) {
    if (IntServer == undefined || Data == undefined) {
        return;
    }
    ServerArr[IntServer].write(Data)
}
exports.SocketReadyState = function (IntServer) {
    if (IntServer == undefined) {
        return;
    }
    if (ServerArr[IntServer].readyState == "opening") {
        return "正在连接";
    }
    if (ServerArr[IntServer].readyState == "open") {
        return "连接状态";
    }
    if (ServerArr[IntServer].readyState == "closed") {
        return "断开状态";
    }
    if (ServerArr[IntServer].readyState == "readOnly") {
        return "可读但不可写状态";
    }
    if (ServerArr[IntServer].readyState == "writeOnly") {
        return "不可读写状态";
    }
    return ServerArr[IntServer].readyState;
}
exports.SocketDestroy = function (IntServer) {
    if (IntServer == undefined) {
        return;
    }
    ServerArr[IntServer].destroy()
}
