var mysql      = require('mysql');

var app = null
var pool = null
const connectionLimit = 66


exports.init = function(express) {  
  app = express
  
  app.get('LOG').log('Database | Server to connect to is ' + app.get('CONF').database.host + '')
  
  pool = mysql.createPool({
    connectionLimit : connectionLimit,
  	host     : app.get('CONF').database.host,
  	port     : app.get('CONF').database.port,
  	database : app.get('CONF').database.database,
  	user     : app.get('CONF').database.user,
  	password : app.get('CONF').database.password,
  	waitForConnections : true
  });
  
  var connectionCountTemp = 0;
  setInterval(function() {
    const connectionCount = pool._freeConnections.length
    if(connectionCount != connectionCountTemp) {
      connectionCountTemp = connectionCount
      
      if(connectionCount > (connectionLimit / 2)) {
        app.get('LOG').error(`Database | Connection count: ${connectionCount}`)
      } else {
        app.get('LOG').debug(`Connection count: ${connectionCount}`) 
      }
    }
  }, 1000)
  
	return this;
}

exports.getItem = function(identifier, callback) {
  const sql = `SELECT * FROM items WHERE identifier = '${identifier}'`
  
  pool.query(sql, function (error, results, fields) {
    if (error) throw error;
    
    callback(results[0])
  });
}

exports.getItemList = function(callback) {
  const sql = `SELECT * FROM items i ORDER BY i.order ASC`
  
  pool.query(sql, function (error, results, fields) {
    if (error) throw error;
    
    callback(results)
  });
}

exports.getNotAvailableList = function(itemID, callback) {
  const sql = `SELECT a.item, a.from AS 'start', a.to as 'end' FROM available a WHERE a.item = ${itemID} ORDER BY a.from ASC`
  
  pool.query(sql, function (error, results, fields) {
    if (error) throw error;
    
    callback(results)
  });
}