# libraries
bcrypt = require('bcrypt')
express = require('express')
helmet = require('helmet')
http = require('http')
mysql = require('mysql')
path = require('path')
socketio = require('socket.io')

# socket.io framework
app = express()
web = http.Server(app)
io = socketio(web)

# Listen server
web.listen 8080, ->
  console.log 'Node.js listening on port 8080'
  return

app.use helmet()

# Static content
app.use express.static path.resolve(__dirname, 'public_html')

# Templates
app.set 'view engine', 'pug'
app.get '/:template.html', (req, res) ->
  res.render (req.params.template + '.pug')

con = mysql.createConnection
  host: 'tcgsql'
  user: 'fftcg'
  database: 'fftcg'
  password: 'juchie5OhH6eiQuujaoquievezoe9iXe'

con.connect (err) ->
  if err
    throw err
  console.log 'Connected to TCGSQL!'
  return

# Server logic
io.on 'connection', (socket) ->

  console.log 'a user connected'

  socket.on 'disconnect', ->
    # console.log('user disconnected');
    return

  socket.on 'login', (msg) ->
    console.log 'message:', msg.uname, msg.password
    saltRounds = 13

    bcrypt.hash msg.password, saltRounds, (err, hash) ->
      con.query 'INSERT INTO `users` (nick, pwd_hash) VALUES (\'' + msg.uname + '\', \'' + hash + '\');', (err, result) ->
        if err
          throw err
        console.log 'Result: ' + result
        return
      return

    return

  return
