###
Handles the Connection to the Database.

This is our Abstraction Layer for the Database
###

mysql = require 'mysql'

# Object to return
con_db = {}

###
Return a Connection to the Database 
###
con_db.connect = con_db.open = (host, database, username, password) ->

	# Create our Connection
	connection = mysql.createConnection {
		host     : host,
		user     : username,
		password : password,
		database: database
	}

	# Connect to the Database
	connection.connect()

	# On Error
	connection.on 'error', (err) ->
		if not err.fatal
			return

		if err.code is not 'PROTOCOL_CONNECTION_LOST'
			throw err

		console.log 'Re-Connecting, lost the connection: ' + err.stack

		connection = mysql.createConnection(connection.config);
		connection.connect()

	return connection

###
Close a Connection to the database
###
con_db.disconnect = con_db.close = (connection) ->

	# Close the Connection
	connection.destroy()

	# Tell the caller that we were succesfull while closing the connection
	return true

module.exports = exports = con_db
