local m_helpers = require "helpers"
local Repository = require "icc_repository"
local m_initialized = false

module(..., package.seeall)

local function MakeCassandraConn ()
	return {
		host = os.getenv("CASSANDRA_IP"),
		port = tonumber(os.getenv("CASSANDRA_PORT"))
	}
end

local function MakeCompatibleLogger ()
	return {
		debug = LogDebug,
		info  = LogInfo,
		warn  = LogWarning,
		error = LogError,
		fatal = LogFatal,
	}
end

function Init (self)
	if m_initialized then
		--LogDebug("[INTERACTIONMAINIP.repository.Init] --> Already intialized.....")
		return
	end
	local config = MakeCassandraConn()
	LogInfo("[INTERACTIONMAINIP.repository.Init] Initializing Repository. Config: '%s'", m_helpers.table:JSON_Encode(config))
	Repository.init({cassandra = config, logger = MakeCompatibleLogger()})
	m_initialized = true
end

function RetrieveFile (self, info)
	assert(info)
	assert(info.id)
	local section = info.section or 0
	local part = info.part or 0

	local success, encodedConversation = Repository.retrieve_file(info.id, section, part, false)
	--LogDebug("[INTERACTIONMAINIP.repository.RetrieveFile] Retrieved file. id: '%s', section: '%s', part: '%s', success: '%s', encodedConversation:\n%s", info.id, section, part, success, encodedConversation)
	if not success then
		return false
	end
	local conversation = m_helpers.table:JSON_Decode(encodedConversation)
	return true, conversation, encodedConversation
end
