# node libraries
express = (require 'express')
path = (require 'path')

# my libraries
FFTCGDB = (require './db')
FFTCGLOG = new (require './console')('FFTCGROUTER')

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

# create router
FFTCGROUTER = express.Router()

# request logging
FFTCGROUTER.use (req, res, next) ->
  if req.session.user
    FFTCGLOG.log "user '#{req.session.user.login}' requested '#{req.url}'"
  else
    FFTCGLOG.log "requested '#{req.url}'"

  next()

# static content
FFTCGROUTER.use express.static path.resolve(__dirname, '../public_html')

# register user
FFTCGROUTER.post '/register', (req, res) ->
  fftcgdb.register req.body.login, req.body.password
    .then (user) ->
      # registration successful, return JSON status
      res.json
        status: 'ok'
        user: user.user
        login: user.login

    .catch (err) ->
      # registration failed, return JSON status
      res.json
        status: 'fail'
        text: err

# log in user
FFTCGROUTER.post '/login', (req, res) ->
  fftcgdb.login req.body.login, req.body.password
    .then (user) ->
      # login successful, save stuff in session
      req.session.user = user
      req.session.save()

      # return JSON status
      res.json
        status: 'ok'
        user: user.user
        login: user.login

    .catch (err) ->
      # login failed, return JSON status
      res.json
        status: 'fail'
        text: err

# Templates
FFTCGROUTER.get '/:template.html', (req, res) ->
  # redirect logged-in users to user cp
  if req.session.user and req.params.template == 'index'
    return res.redirect '/usercp.html'

  # render requested template
  res.render (req.params.template + '.pug'), (err, html) ->
    # redirect invalid requests to index
    if err
      return res.redirect '/index.html'

    # actual response
    res.send html

# default route
FFTCGROUTER.use (req, res) ->
  return res.redirect '/index.html'

module.exports = FFTCGROUTER
