const net = require("net") const RPL_WELCOME = '001' const ERR_NOSUCHNICK = '401' const ERR_NOSUCHCHANNEL = '403' const ERR_CANNOTSENDTOCHAN = '404' const ERR_UNKNOWNCOMMAND = '421' const ERR_ERRONEUSNICKNAME = '432' const ERR_NICKNAMEINUSE = '433' const ERR_NEEDMOREPARAMS = '461' let server = {} let userlist = { 0: { "nick": "chris", 1: "some value" }, 1: { "nick": "wayne", 1: "some_other_value" } } server.create = function create() { return net.createServer((socket) => { socket.on('data', function (data) { let tokenized = data.toString("ascii").split("\r\n")[0].split(" ") switch (tokenized[0].toUpperCase()) { case "PING": if (tokenized[1] && tokenized[1] === "irc.example.com") { socket.write("PONG irc.example.com\r\n") } break; case "NICK": if (tokenized[1]) { let nickname = tokenized[1] let nickNameCollision = 0 for (let clientID in userlist) { console.log(clientID) if (userlist[clientID]["nick"] === nickname) { nickNameCollision = 1 delete userlist[clientID] } } if (!nickNameCollision) { let index = Object.keys(userlist).length userlist[index] = { "nick": nickname } socket.write(RPL_WELCOME, " nick " + nickname + " succesfully added.") } else { socket.write(ERR_NICKNAMEINUSE, " nickname in use") } } else { socket.write("ERROR: NO NICKNAME PROVIDED") } break; default: console.error(`Unknown command: ${tokenized[0].toUpperCase()}`); } }).on('error', (err) => { console.error(err); }) }).on('error', (err) => { console.error(err); throw err; }); } module.exports = server