# node libraries
# (require 'debug').enable 'FFTCG'
logger = (require 'logging').default 'FFTCG'
fastify = (require 'fastify')
  logger: level: 'warn'

# fastify and plugin framework
fastify.register (require 'fastify-cookie')
fastify.register (require 'fastify-ws'), library: 'uws'

# temporary dev frontend; to be uninstalled
path = (require 'path')
fastify.register (require 'fastify-static'), root: (path.join __dirname, 'tmpfront')

# API routes
fastify.route (require "./routes/#{route}") for route in [
  # test route
  'test'
  # log in user
  'user/login'
  # register user
  'user/register'
]

# request logging
fastify.addHook 'onRequest', (req, res, next) ->
  logger.debug 'requested', req.url
  next()

# finalize loadup
fastify.ready()
  .then ->
    # create websocket on successful load
    socket = (require './socket')
    fastify.ws.on 'connection', socket

  .catch (err) ->
    # abort on load failure
    logger.error err
    process.exit 1

# start server
fastify.listen 3001, '0.0.0.0'
  .catch (err) ->
    logger.error err

# Handle termination
process.on 'SIGINT', ->
  socket.close()
  logger.info 'shutting down after SIGINT'
  process.exit()
