const mysql = require('mysql');

const constants = require('./config/constants');
const _ = require('lodash');
const emoji = require('node-emoji');

const connection = mysql.createConnection({
  host: constants.DB_URL,
  user: constants.DB_USERNAME,
  password: constants.DB_PASSWORD,
  database: constants.DB,
  charset: 'utf8mb4',
});

connection.connect((err) => {
  if (err) {
    console.log('Error connecting to database.');
    console.log(err.stack);
    return;
  }
  console.log('Connected to database.');
});

function logMessage(msg) {
  connection.query('INSERT INTO messages (message, userId, channelId, username, time) values(?, ?, ?, ?, ?)',
  [msg.content, msg.author.id, msg.channel.id, msg.author.username, new Date()], (err) => {
    if (err) throw err;
  });
}

function logCommand(command, parameters, msg, executionTime, ownCommand) {
  let parameter = null;
  if (parameters.length !== 0) {
    parameter = parameters.join(' ');
  }
  connection.query(
    'INSERT INTO commands (command, parameters, username, user_id, channel_id, guild_id, execution_time, time, own_command) values(?, ?, ?, ?, ?, ?, ?, ?, ?)',
  [command, parameter, msg.author.username, msg.author.id, msg.channel.id, msg.guild.id, executionTime, new Date(), ownCommand], (err) => {
    if (err) throw err;
  }
);
}

function randomName(client) {
  setInterval(() => {
    const count = 1;
    connection.query(`CALL get_rands(${count}, ${constants.BEST_SERVER})`, (err, result) => {
      if (err && result.length === 0) return;
      let name = 'Mörkö';
      result.forEach((q, i) => {
        if (i + 1 === result.length) return;
        if (q[0]) {
          if (q[0].message) {
            const words = q[0].message.split(' ');
            const rand = Math.floor(Math.random() * words.length);
            if (words[rand].length >= 25) {
              name = words[rand].substr(0, 25);
            } else {
              name = words[rand];
            }
          }
        }
      });
      if (name.length === 0) return;
      const firstEmoji = emoji.random();
      const secondEmoji = emoji.random();
      let emojiName = `${firstEmoji.emoji} ${name} ${secondEmoji.emoji}`;
      if (emojiName.length > 32) {
        emojiName = `${firstEmoji.emoji} ${name}`;
        if (emojiName.length > 32) {
          emojiName = name;
        }
      }
      const guild = client.guilds.get(constants.BEST_SERVER);
      if (!_.isNil(guild)) {
        guild.members.get(client.user.id)
        .setNickname(emojiName)
        .then(() => {
          console.log('New name: ' + emojiName);
        })
        .catch((error) => {
          console.log(error);
        });
      }
    });
  }, 3600000); // 60 minutes
}

module.exports = {
  connection,
  logMessage,
  logCommand,
  randomName,
};

@@ -145,51 +145,75 @@
 ');%0A
-%0A
 const 
-connection = mysql.createConnection(
+logger = require('./src/utility/utility');%0A%0Aconst dbConfig = 
 %7B%0A  
@@ -351,20 +351,298 @@
 8mb4',%0A%7D
-)
 ;%0A%0A
+let connection;%0A%0A// Source: https://stackoverflow.com/questions/20210522/nodejs-mysql-error-connection-lost-the-server-closed-the-connection%0Afunction handleDisconnect() %7B%0A  logger.logMessage('Connecting to database.', 'info');%0A  connection = mysql.createConnection(dbConfig);%0A%0A  
 connecti
@@ -663,16 +663,18 @@
 r) =%3E %7B%0A
+  
   if (er
@@ -686,27 +686,40 @@
     
-console.log('
+  logger.logMessage(%60
 Error 
+when 
 conn
@@ -733,106 +733,409 @@
 to d
-atabase.');%0A    console.log(err.stack);%0A    return;
+b: Error: $%7Berr%7D%60, 'error');%0A      setTimeout(handleDisconnect, 2000);%0A    %7D else %7B%0A      logger.logMessage('Connected to DB.', 'info');%0A    %7D
 %0A  %7D
+);%0A
 %0A  con
-sole.log('Connected to database.');%0A%7D
+nection.on('error', (err) =%3E %7B%0A    logger.logMessage(%60DB error: Error: $%7Berr%7D%60, 'error');%0A    if (err.code === 'PROTOCOL_CONNECTION_LOST') %7B%0A      handleDisconnect();%0A    %7D else %7B%0A      throw err;%0A    %7D%0A  %7D);%0A%7D%0A%0A// Connect to DB%0AhandleDisconnect(
 );%0A%0A
@@ -1271,16 +1271,18 @@
 ?, ?)',%0A
+  
   %5Bmsg.c
@@ -1361,32 +1361,34 @@
  (err) =%3E %7B%0A    
+  
 if (err) throw e
@@ -1391,16 +1391,18 @@
 ow err;%0A
+  
   %7D);%0A%7D%0A
@@ -1756,16 +1756,18 @@
 ?, ?)',%0A
+  
   %5Bcomma
@@ -1894,32 +1894,34 @@
  (err) =%3E %7B%0A    
+  
 if (err) throw e
@@ -1926,18 +1926,22 @@
  err;%0A  
-%7D%0A
+  %7D%0A  
 );%0A%7D%0A%0Afu
@@ -3120,16 +3120,18 @@
         
+  
 .setNick
@@ -3146,16 +3146,18 @@
 jiName)%0A
+  
         
@@ -3172,32 +3172,34 @@
  =%3E %7B%0A          
+  
 console.log('New
@@ -3233,11 +3233,15 @@
     
+ 
+ 
 %7D)%0A
+  
     
@@ -3266,32 +3266,34 @@
  =%3E %7B%0A          
+  
 console.log(erro
@@ -3296,16 +3296,18 @@
 error);%0A
+  
         
@@ -3431,13 +3431,12 @@
 ndomName,%0A%7D;
-%0A

Handle DB disconnects