--
-- Small module for luanode applications
--

local Redis = require "redis-luanode"
local json = require "cjson"
local helpers = require "presencefilter.helpers"

local EventEmitter = require "luanode.event_emitter"

local Async = EventEmitter()

local m_redis_client = nil
local m_logger = nil

local function no_op() end

function Async.Initialize (options)
	m_redis_client = Redis.createClient(options.redis_port, options.redis_ip, { pwd = options.redis_pwd })

	m_logger = options.logger or console

	m_redis_client:on("connect", function()
		Async:emit("ready")
	end)

	m_redis_client:on("error", function(self, msg)
		m_logger.error(msg)
	end)
	
	m_redis_client:on("reconnecting", function(self)
		Async:emit("not_ready")
	end)

end

function Async.Update (authUser, callback)
	local session_token = authUser.sid
	local session_key = helpers.get_user_session_time_key(authUser)
	callback = callback or no_op
	local new_timestamp = os.time()
	
	m_redis_client:zadd(session_key, new_timestamp, session_token, function(self, err, reply)
		m_logger.debug("[presence] Updated timestamp for key '%s' session '%s' with value '%s'", 
			session_key, session_token, new_timestamp)
		no_op(err, reply)
	end)
end


return Async
