require "socket" 
local http = require "socket.http" 
local ltn12 = require "ltn12" 

module(..., package.seeall)

local m_allegroConfig
local function SetAllegroConfig (allegroConfig)
    m_allegroConfig = allegroConfig
end

local function GetAllegroConfig ()
    return m_allegroConfig
end

local function BuildCompletePath (url)
	return "/inconcert/apps/" .. url
end

local function BuildCompleteUrl (url, ip, port)
	return string.format("http://%s:%s%s", ip, port, BuildCompletePath(url))
end

local function Get (url, headers, cookie, ip, port, getHeaders)
	local uri = BuildCompleteUrl(url, ip, port)
	-- LogDebug("")
	-- LogDebug("-- GET start --")
	-- LogDebug("GET URI: %s", uri)
	headers = headers or {}
	if cookie and string.len(cookie) then
		headers["Cookie"] = cookie
	end
	--LogDebug("GET -> headers; %s", json.encode(headers))
	local responseBody = {}
	local result, code, header = http.request{
		url = uri,
		method = "GET",
		headers = headers,
		sink = ltn12.sink.table(responseBody)
	}
	local response = table.concat(responseBody, "")
	--LogDebug("GET-> result: '%s', code: '%s', header: '%s'.", result, code, json.encode(header))
	--LogDebug("GET-> response length: '%s'", #(response or ""))

	if code == 200 then
		if getHeaders then
			return  true, { headers = header, file = response }
		end

		return true, response
    end
	LogError("[REPOSITORY.ALLEGRO_REPOSITORY:Get] Result: '%s', code: '%s', header: '%s'.", result, code, json.encode(header))
	return false, response, code
end

function Retrieve (self, vcc, id, section, part, stream, getHeaders)
    LogInfo("[REPOSITORY.ALLEGRO_REPOSITORY:Retrieve] Retrieving Allegro Repository. vcc: '%s', id: '%s',section: '%s',part: '%s',stream: '%s', getHeaders: %s", vcc, id, section, part, stream, getHeaders)
	local allegroConfig = GetAllegroConfig(vcc)
	if not allegroConfig or not allegroConfig.webhandlerInfo then
		LogWarning("[REPOSITORY.ALLEGRO_REPOSITORY:Retrieve] Unable to retrieve allegroConfig.webhandlerInfo %s", allegroConfig)
		return false
	end

	local url = "mediaserver/action/download/repository/" .. id .. "/" .. section .. "/" .. part .. "/"
	local webhandler_ip = allegroConfig.webhandlerInfo.ip
	local webhandler_port = allegroConfig.webhandlerInfo.port
	local headers = {}
	local cookie = allegroConfig.webhandlerInfo.credentials

    if stream then
        assert(false, "TODO: Implement Stream")
		--return StreamGet(url, headers, cookie, webhandler_ip, webhandler_port)
	else
		return Get(url, headers, cookie, webhandler_ip, webhandler_port, getHeaders)
	end
end

function Initialize (self, options)
	LogInfo("[REPOSITORY.ALLEGRO_REPOSITORY:Initialize] Initializing Allegro Repository Config. '%s'", options.allegroConfig)
	--for _,v in pairs(options) do
	--	LogInfo("-->: '%s' = '%s'", _,v)
	--end
    if not options.allegroConfig then
        return false
    end
    SetAllegroConfig(options.allegroConfig)
    return true
end
