-- url : (string, read-only) copy of target url that httpRequestFunc will hit
-- httpRequestFunc : (function<dictionary>(void))

local function commonHttpHandler(url, httpRequestFunc)
	assert(type(url) == "string", "expected 'url' to be a string")
	assert(type(httpRequestFunc) == "function", "expected 'httpRequestFunc' to be a function")

	local p = Promise.new(function(resolve, reject)

		spawn(function()
			local startTime = tick()
			local success, resultDict = pcall(httpRequestFunc)
			local endTime = tick()
			local deltaMs = (endTime - startTime) * 1000

			if success then
				local body = resultDict["Body"]
				local requestSuccess = resultDict["Success"]
				local statusMsg = resultDict["StatusMessage"]
				local statusCode = resultDict["StatusCode"]

				if requestSuccess == true then
					resolve(HttpResponse.new(body, statusCode, deltaMs))
				else
					reject(HttpError.new(url, statusMsg, body, statusCode, deltaMs))
				end
			else
				-- the request timed out, or something went wrong
				reject(HttpResponse.new(url, "Unknown Error", resultDict, 500, deltaMs))
			end

			if DEBUG_HTTP then
				local msg = table.concat(
				{
					"--------------------------",
					"Fetching Url :" .. url, "",
					"Success :" .. tostring(success), "",
					"Result :", recursiveToString(resultDict),
					"--------------------------"
				}, "\n")
				print(msg)
			end
		end)
	end)

	return p
end



local Networking = {}
Networking.__index = Networking
