# node libraries
redis = (require 'redis')
crypto = (require 'crypto')
logger = (require 'logging').default 'session'

# expiry times in days
EXPIRY =
  # games expire 1 week after creation
  game:    7
  # logins expire 1 month after last action
  login:   30


class FFTCGSESSION
  constructor: ->
    @db = redis.createClient
      host: 'redis'
      port: 6379

    @db.on 'error', (err) =>
      logger.error err.message

  start: (data) ->
    new Promise (resolve) =>
      # hash data
      hmac = crypto.createHmac 'sha256', Math.random().toString()
      hmac.update (JSON.stringify data)
      digest = hmac.digest 'base64'
      logger.debug 'digest', digest

      # push (hash, data) into DB for the configured timespan
      @db.setex digest, EXPIRY.login * 86400, (JSON.stringify data), (err) ->
        logger.info "OK '#{digest}' created"
        # return cookie data
        resolve
          value:  digest
          properties:
            expires:  EXPIRY.login

  destroy: (digest) ->
    new Promise (resolve, reject) =>
      # delete hash immediately
      @db.del digest, (err, res) ->
        if res == 0
          reject null
        else
          logger.info "OK '#{digest}' deleted"
          resolve null

  check: (digest) ->
    new Promise (resolve, reject) =>
      # refresh expiry timer on digest
      @db.expire digest, EXPIRY.login * 86400, (err, res) =>
        if res == 0
          reject null

        else
          @db.get digest, (err, res) ->
            logger.debug "OK '#{digest}' resumed"
            resolve (JSON.parse res)

module.exports = new FFTCGSESSION
