local allegroProxy = require "lua_allegroproxyclient"

module(..., package.seeall)

local m_allegroClient

local function GetAllegroClient ()
	--LogDebug("1 GetAllegroClient")
	if not m_allegroClient then
		local allegroProxyConfig = inconcert.environment.apps.agent.allegroproxy
		LogInfo("[REPORTER.ALLEGRO.GetAllegroClient] Creating Allegro Proxy. Cluster: %s, allegroProxy: '%s'", inconcert.environment.apps.agent.cluster, json.encode(allegroProxyConfig or {}))
		if allegroProxyConfig then
			m_allegroClient = allegroProxy.LuaAllegroProxyClient(inconcert.environment.apps.agent.cluster, "webhandler")
			for _, address in pairs(allegroProxyConfig) do
				LogInfo("[REPORTER.ALLEGRO.GetAllegroClient] Add Known Allegro Proxy. Cluster. IP: '%s', Port: '%s'.", address.ip, address.port)
				m_allegroClient:AddKnownAllegroProxy(address.ip, address.port)
			end
		else
			LogWarning("[REPORTER.ALLEGRO.GetAllegroClient] There is no allegro configuration")
		end
	end
	--LogDebug("2 GetAllegroClient %s", m_allegroClient)
	return m_allegroClient
end

function GetWebhandlerInfo (vcc)
	local allegroClient = GetAllegroClient()
	if not allegroClient then
		return
	end
	local webhandlerInfo, err = allegroClient:GetWebhandlerInfo(vcc)

	if not webhandlerInfo then
		if not err then
			err = { type = "ALLEGRO_INTEGRATION_ERROR", sub_type = "RETRIEVING_ALLEGRO_CREDENTIALS" }
		end
		LogWarning("[REPORTER.ALLEGRO:GetWebhandlerInfo] Error retrieving allegro credentials, VCC: '%s'. Err: '%s'", vcc, err)
		return false, err
	end

	LogInfo("[REPORTER.ALLEGRO:GetWebhandlerInfo] Allegro credentials: '%s'", json.encode(webhandlerInfo))
	return webhandlerInfo
end


