# node libraries
bodyParser = (require 'body-parser')
express = (require 'express')
sharedSession = (require 'express-socket.io-session')
helmet = (require 'helmet')
http = (require 'http')
path = (require 'path')

# my libraries
FFTCGSOCKET = (require './inc/fftcgsocket')
FFTCGDB = (require './inc/fftcgdb')
FFTCGSESSION = (require './inc/fftcgsession')

# express framework
app = express()
app.use helmet()
app.use bodyParser.urlencoded
  extended: true

# sessions
sessionMiddleware = FFTCGSESSION(app)
app.use sessionMiddleware

# open fftcg db
fftcgdb = new FFTCGDB path.resolve(__dirname, './fftcg.db')

app.post '/register', (req, res) ->
  fftcgdb.register req.body.login, req.body.password
    .then (userid) ->
      console.log "registered '#{req.body.login}'"
      res.json
        status: 'ok'
        uid: userid
        text: req.body.login
    .catch (err) ->
      console.log "failed to register '#{req.body.login}'"
      res.json
        status: 'fail'
        text: err

app.post '/login', (req, res) ->
  fftcgdb.login req.body.login, req.body.password
    .then (userid) ->
      req.session.userID = userid
      req.session.save()
      console.log "logged in '#{req.body.login}'"
      res.json
        status: 'ok'
        uid: userid
        text: req.body.login
    .catch (err) ->
      console.log "failed to login '#{req.body.login}'"
      res.json
        status: 'fail'
        text: err

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

# Templates
app.set 'view engine', 'pug'
app.get '/:template.html', (req, res) ->
  if req.session
    console.log "logged in as '#{req.session.userID}'"
  res.render (req.params.template + '.pug')

# Create server
web = http.Server app
web.listen 3000, ->
  console.log '[FFTCG] Listening on port 3000 ...'

# socket.io
socket = new FFTCGSOCKET web, sharedSession sessionMiddleware

# Handle termination
process.on 'SIGINT', ->
  socket.close()
  console.log '[FFTCG] shutting down after SIGINT'
  process.exit()
