--
-- Small module for luanode applications
--
local Redis = require "redis-luanode"
local json = require "cjson"
local EventEmitter = require "luanode.event_emitter"
local Async = EventEmitter()

module(..., package.seeall)

local m_redis = nil
local m_logger = nil

Async.INVALID_CREDENTIALS = {}

function Async.Initialize (options)
	m_logger = options.logger or console

	m_redis = Redis.createClient(options.redis_port, options.redis_ip, { pwd = options.redis_pwd })
	m_redis:on("connect", function()
		Async:emit("ready")
	end)
	m_redis:on("error", function(self, msg)
		m_logger.error("[AUTHFILTER.Async.Initialize] " .. tostring(msg))
	end)
	m_redis:on("reconnecting", function(self)
		Async:emit("not_ready")
	end)
end

--
-- Get user information from apps credentials
--
function Async.GetUserFromCredentials (appName, credentials, callback)
	appName = appName:upper()

	--this key must be consistent with the one defined in authfilter.lua
	local key = "authFilter:userBySID:"..appName

	m_redis:hget(key, credentials, function(self, err, reply)
		if err then
			m_logger.warn("[AUTHFILTER.Async.GetUserFromCredentials] Error in authfilter.async.GetUserFromCredentials: %s", err)
			callback(err)
		else
			if not reply then
				--callback(nil, "Invalid credentials")
				callback(nil, Async.INVALID_CREDENTIALS)
				return
			end
			local ok, userInfo = pcall(json.decode, reply)
			if ok then
				local userId = userInfo.id or ""
				m_logger.profile("[AUTHFILTER.Async.GetUserFromCredentials] credentials %s for app %s belongs to user %s", credentials, appName, userId)
				callback(nil, userInfo)
			else
				m_logger.error("[AUTHFILTER.Async.GetUserFromCredentials] UserInfo from redis is corrupt: userInfo [%s]", reply)
				m_logger.error("[AUTHFILTER.Async.GetUserFromCredentials] Error is: [%s]", userInfo)
				callback("UserInfo is corrupt")
			end
		end
	end)
end

--
-- Get cookie name and value for specific app
--
function Async.GetCookieForApp (appName, credentials)
	--this cookie must be consistent with the one defined in authfilter.lua
	return "AUTH_SID_"..appName:upper().."="..credentials
end

return Async
