 xml2js = require 'xml2js'
 Q = require 'q'
 utils = require '../utils'
+database = require '../database'
 
 logger = utils.logging.newConsoleLogger module.filename
+
+redisConnection = database.getConnection()
 
 authenticationHandler = (req, res, next) ->
   token = 'EastIndiaCompany'

      tag = content[..separatorIndex - 1]
      request = content[separatorIndex + 1..]
      payload =
        toUser: fromUser
        fromUser: toUser
        createTime: createTime
        request: request
      rpcCall tag, payload, sendResponse

  .done()

rpcCall = (tag, payload, sendResponse) ->
  if tag == 'echo'
    sendResponse "echo #{payload.request}"
  else if tag == 'login'
    if payload.request.match /[^0-9a-z]/i
      sendResponse 'only letters and digits allowed'
    else
      Q.ninvoke redisConnection, 'hset', 'login', request.fromUser, payload.request
      sendResponse 'OK'
  else if tag == 'summary'
    Q.ninvoke redisConnection, 'hget', 'login', request.fromUser
    .then (id) ->
      if not id
        sendResponse 'please login first'
      else
        sendResponse "http://myap.ml/?id=#{id}"
  else
    sendResponse "invalid tag #{tag}"

