--[[
	https://icqnamaker.azurewebsites.net/qnamaker/knowledgebases/05f0f448-b328-4f0c-b2c2-57f90078acd3/generateAnswer
	https://icqnamaker.azurewebsites.net/qnamaker/knowledgebases/05f0f448-b328-4f0c-b2c2-57f90078acd3/generateAnswer

	https://icqnamaker.azurewebsites.net/qnamaker//knowledgebases/05f0f448-b328-4f0c-b2c2-57f90078acd3/generateAnswer


	-----------------------

	:"6c0aa9ff967b4833ad3018557272547e"}'.
	[INFO ] [QNA_MAKER_KNOWLEDGEBASE:Load] Success Loaded Knowledgebases.
	[DEBUG] [QNA_MAKER_API:GenerateAnswer] Buscando VCC kbId '05f0f448-b328-4f0c-b2c2-57f90078acd3' en la BD de QnA Maker.
	[INFO ] [QNA_MAKER.REQUEST:Post] POST Request retry 1 of 3. URI: 'https://icqnamaker.azurewebsites.net/qnamaker/knowledgebases/05f0f448-b328-4f0c-b2c2-57f90078acd3/generateAnswer"', headers: '{"Content-Type":"application\/json","Authorization":"EndpointKey b86abe85-a840-44bd-91c9-728892b2ea2e"}', body: '{"question":"pregunta"}'
]]--


--[[

CURL Sample:
	curl -X POST -k -H "Content-type: application/json" -H "Authorization: EndpointKey b86abe85-a840-44bd-91c9-728892b2ea2e" -d "{'question':'nombre'}" https://icqnamaker.azurewebsites.net/qnamaker/knowledgebases/05f0f448-b328-4f0c-b2c2-57f90078acd3/generateAnswer

	os.execute('curl -X POST -k -H "Content-type: application/json" -H "Authorization: EndpointKey b86abe85-a840-44bd-91c9-728892b2ea2e" -d "{\'question\':\'nombre\'}" https://icqnamaker.azurewebsites.net/qnamaker/knowledgebases/05f0f448-b328-4f0c-b2c2-57f90078acd3/generateAnswer')
]]

local Synchronize = require "Synchronize"
local https = Synchronize("luasec_mutex", function()
	return require ("ssl.https")
end)
--local https = require("socket.http")
--local https = require("socket.https")

local ltn12 = require "ltn12"
local json = require "cjson"

local function LogArgumentsFormatter (...)
	local args = {...}
	for i=1, select("#", ...) do
		local arg = args[i]
		local arg_type = type(arg)
		if arg_type ~= "string" and arg_type ~= "number" then
			args[i] = tostring(arg)
		end
	end
	return unpack(args)
end

LogDebug = LogDebug or function (fmt, ...)
	local msg = string.format(fmt, LogArgumentsFormatter(...))
	print("[DEBUG] " .. msg)
end

function Post (uri, body, headers)
	local encodedBody = json.encode(body)
	LogDebug("[QNA_MAKER.REQUEST:Post] POST Request retry URI: '%s', headers: '%s', body: '%s'", uri, json.encode(headers), encodedBody)

	local response = {}
	local params = {
-- mode = "client",
-- protocol = "tlsv1",
-- verify = "none",
-- options = "all",
		url = uri,
		method = "POST",
		headers = headers,
		source = ltn12.source.string(encodedBody),
		-- --respuesta
		sink = ltn12.sink.table(response)
	}
	local result, code, header, statusline = https.request(params)

-- require("socket")
-- local ssl = require("ssl")

-- -- TLS/SSL client parameters (omitted)
-- -- local params = {
  -- -- mode = "client",
  -- -- protocol = "tlsv1",
  -- -- verify = "none",
  -- -- options = "all",
-- -- }

-- local conn = socket.tcp()
-- conn:connect(uri, 443)
-- -- TLS/SSL initialization
-- conn = ssl.wrap(conn, params)
-- conn:dohandshake()

-- conn:send("POST / HTTP/1.1\n\n")
-- local line, err = conn:receive()
-- print(err or line)
-- conn:close()

	LogDebug("[QNA_MAKER.REQUEST:Post] POST request result: '%s', code: '%s' headers: '%s' , statusline: '%s', response: '%s'", result, code, json.encode(header or {}), statusline, json.encode(response))
end

local kbId = "8b281447-37c7-4e85-9d7f-b71f49970b55" -- EL ID DE LA KB

local URI = string.format("https://icqnamaker.azurewebsites.net/qnamaker/knowledgebases/%s/generateAnswer", kbId)
local BODY = {
	top = 30,
	question="estacionamiento",
	-- -- metadata
	strictFilters = {
		{name = "ciudad", value = "colonia"}
	},
	strictFiltersCompoundOperationType = "OR" -- OR o AND
}
local HEADERS = {}
local encodedBody = json.encode(BODY)
HEADERS["Content-Type"] = "application/json"
HEADERS["Content-Length"] = #encodedBody
HEADERS["Authorization"] = "EndpointKey b86abe85-a840-44bd-91c9-728892b2ea2e"


print("")
print("")
LogDebug("---------------------------------------------------------------")
LogDebug("1 - CURL ---------------------------------------------------------------")
LogDebug("--")
local cmd = string.format([[curl -X POST -k -H 'Content-type: %s' -H 'Authorization: %s' -d '%s' %s]],
	HEADERS["Content-Type"],
	HEADERS["Authorization"],
	encodedBody,
	URI
)
print(cmd)
os.execute(cmd)
print("")
print("")
print("res= " .. tostring(res))
print("res1= " .. tostring(res1))
print("")
print("")
print("")
LogDebug("---------------------------------------------------------------")
LogDebug("2 - SSL ---------------------------------------------------------------")
LogDebug("--")

Post (URI, BODY, HEADERS)