--[[
Ejemplo:
	lua test.lua 192.168.4.11

	donde 192.168.4.11 es la ip de cassandra
]]--
require "json"
require "socket"

local cassandra = require "lua_cassandra"
local cassandraHost = arg[1] or "127.0.0.1"
local cassandraPort = arg[2] or 9160
print("Connecting CASSANDRA " .. tostring(cassandraHost) .. ":" .. tostring(cassandraPort))
cassandra.seed(cassandraHost, cassandraPort)

local apiQnAMaker = require "qna_maker"
apiQnAMaker.EnableLogger(true)
local models = require("qna_maker.models")
--models.BuildModels()

local function GetKnowledgeBaseGetEndpointKeys (vcc)
	local success, response = apiQnAMaker.GetEndpointKeys(vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
end

local function GetVccKnowledgebase (vcc)
	local success, response = apiQnAMaker.GetVccKnowledgebase(vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
end

local function LoadKnowledgebases (vcc)
	local success, response = apiQnAMaker.LoadKnowledgebases(vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
end

local function LoadKnowledgebasesFromCassandra (vcc)
	local list, total = apiQnAMaker.LoadKnowledgebasesFromCassandra(vcc)
	print("-total: " .. tostring(total))
	print("-list: " .. tostring(json.encode(list or {})))
end

local function DownloadKnowledgebase (kbId, vcc)
	local success, response = apiQnAMaker.DownloadKnowledgebase(kbId, vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
end

local function GetKnowledgebaseDetail (kbId, vcc)
	local success, response = apiQnAMaker.GetKnowledgebaseDetail(kbId, vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
end

local function GetKnowledgeBaseOperationDetails (operationId, vcc)
	local success, response = apiQnAMaker.GetOperationDetails(operationId, vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
end

local function CreateKnowledgeBase (name, vcc)
	local info = {
		name = name
	}
	local success, response = apiQnAMaker.CreateKnowledgeBase(info, vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
	if success then
		GetKnowledgeBaseOperationDetails(response.operationId, vcc)
	end
end

local function CreateAndWaitKnowledgeBase (name, vcc)
	local info = {
		name = name
	}
	local success, response = apiQnAMaker.CreateAndWaitKnowledgeBase(info, vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(json.encode(response)))
end

local function UpdateKnowledgeBase (info, vcc)
	local success, response = apiQnAMaker.UpdateKnowledgeBase(info, vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
	if success then
		GetKnowledgeBaseOperationDetails(response.operationId, vcc)
		local waitingSec = 15
		print("")
		print("WAITING " .. tostring(waitingSec) .. " seconds .....")
		print("")
		socket.sleep(waitingSec)
		GetKnowledgeBaseOperationDetails(response.operationId, vcc)
	end
end

local function ReplaceKnowledgeBase (info, vcc)
	local success, response = apiQnAMaker.ReplaceKnowledgeBase(info, vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
end

local function DeleteKnowledgeBase (kbId, vcc)
	local success, response = apiQnAMaker.DeleteKnowledgeBase(kbId, vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
end

local function PublishKnowledgeBase (kbId, vcc)
	local success, response = apiQnAMaker.PublishKnowledgeBase(kbId, vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(response))
end

local function LoadVCCSubscriptions (vcc)
	local subscriptionsKeys, total = apiQnAMaker.LoadVCCSubscriptions(vcc)
	print("-total: " .. tostring(total))
	print("-subscriptionsKeys: " .. tostring(json.encode(subscriptionsKeys)))
end

local function LoadVCCsBySubscription (key)
	local vccs, total = apiQnAMaker.LoadVCCsBySubscription(key)
	print("-total: " .. tostring(total))
	print("-vccs: " .. tostring(json.encode(vccs)))
end

local function AssignSubscriptionKeyToVCC (info)
	local success, response = apiQnAMaker.AssignSubscriptionKeyToVCC(info)
	print("-success: " .. tostring(total))
	print("-response: " .. tostring(json.encode(response)))
end

local function UnAssignSubscriptionKeyOfVCC (vcc, key)
	local success, response = apiQnAMaker.UnAssignSubscriptionKeyOfVCC(vcc, key)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(json.encode(response)))
end

local function GenerateAnswer (vcc, info, mustUseCurl)
	local success, response = apiQnAMaker.GenerateAnswer(vcc, info, mustUseCurl)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(json.encode(response)))
end

local function GetAnswerPostInfo (vcc, question)
	local success, response = apiQnAMaker.GetAnswerPostInfo(vcc, question)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(json.encode(response)))
end

local function RemoveKnowledgebaseOnlyCassandra (vcc)
	local success, response = apiQnAMaker.RemoveKnowledgebaseOnlyCassandra(vcc)
	print("-success: " .. tostring(success))
	print("-response: " .. tostring(json.encode(response)))
end

local function VccSupportsQnAMaker (vcc)
	local isSupported = apiQnAMaker.VccSupportsQnAMaker(vcc)
	local supportedMessage = isSupported and "SUPPORT" or "NOT support"
	local message = string.format("VCC '%s' %s QnA Maker.", vcc, supportedMessage)
	print(message)
end

---- TEST 0.4------------------------------------
--[[
	Valida si un VCC Soporta QnA Maker
]]--

--local vcc = "vcc1"
--VccSupportsQnAMaker(vcc)
---------------------------------------------------

-----------------------------
-- local vcc = "vcc1"
-- local databaseName = "test_vcc1_1"

---- TEST 0.5------------------------------------
--[[
	Lista todas las Knowledgebases existentes en QnA Maker.
	Esto sin importar el VCC, el mismo se para por parámetro para poder obtener la key de programación que va en el request.
]]--

--LoadKnowledgebases(vcc)
---------------------------------------------------


---- TEST 0.6------------------------------------
--[[
	Lista todas las Knowledgebases Asociadas al VCC.
	Siempre va a ser 1 sola, pero quizas en algún momento puedan ser más, bueno lo que hace es listar lo que exista en CASSANDRA.
]]--

--LoadKnowledgebasesFromCassandra(vcc)
---------------------------------------------------


---- TEST 0.7------------------------------------
--[[
	Obtiene de CASSANDRA y visualiza información de la única Knowledgebase Asociada al VCC.
]]--

--GetVccKnowledgebase(vcc)
---------------------------------------------------


--local kbId = "b05db7b3-d4e7-4873-b91b-5b23e95b5654"
--local kbId = "af6432c2-292c-4388-a8b7-5198dbb82ca8" -- tito
--local kbId = "9c754f44-3f95-46bc-838d-7c64424a1d76"
--local kbId = "27d1a6b3-99c5-430e-80d3-751c70719d61"
--local kbId = "720ff9b5-5b04-4b89-925a-908a29770af3" -- vcc borrame11
--local kbId = "8b281447-37c7-4e85-9d7f-b71f49970b55"


---- TEST 1------------------------------------
--[[
	Obtiene contra el API y visualiza información de una Knowledgebase.
]]--

-- local kbId = "8b281447-37c7-4e85-9d7f-b71f49970b55"
-- local vcc = "vcc1"
-- DownloadKnowledgebase(kbId, vcc)
---------------------------------------------------

---- TEST 1.1------------------------------------
--[[
	Obtiene contra el API el detalle de la Knowledgebase.
]]--

-- local kbId = "ac44f6af-6598-451f-9cdb-ea3158eaf0a1"
-- local vcc = "vcc1"
-- GetKnowledgebaseDetail(kbId, vcc)
---------------------------------------------------


---- TEST 2------------------------------------
--[[
	Crea una Knowledgebase con lo mímino y necesario.
	La misma NO queda asociada al VCC (NO queda en CASSANDRA).
]]--
-- local vcc = "vcc1"
-- local databaseName = "test_vcc1_1"
--CreateKnowledgeBase(databaseName, vcc)
---------------------------------------------------

---- TEST 2.5------------------------------------
--[[
	Crea una Knowledgebase con lo mímino y necesario.
	La misma SI queda asociada al VCC (SI queda en CASSANDRA)..
]]--
-- local vcc = "vcc1"
-- local databaseName = "test_vcc1_1"
-- CreateAndWaitKnowledgeBase(databaseName, vcc)
---------------------------------------------------


---- TEST 3------------------------------------
--[[
	Elimina una Knowledgebase tanto desde CASSANDRA como contra el API.
]]--
-- local kbId = "8b281447-37c7-4e85-9d7f-b71f49970b55"
-- DeleteKnowledgeBase(kbId, vcc)

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


---- TEST 4------------------------------------
--[[
	Actualiza una Knowledgebase contra el API.
]]--

-- local kbId = "8b281447-37c7-4e85-9d7f-b71f49970b55"
-- local vcc = "vcc1"

-- local updateInfo = {
	-- kbId = kbId,
	-- add = {}
-- }
-- table.insert(updateInfo.add, {
		-- answer = "a - no te interesa !!!",
		-- questions = {
			-- "cual es tu nombre?",
			-- "nombre"
		-- }
	-- }
-- )
-- UpdateKnowledgeBase(updateInfo, vcc)

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

-- ---- TEST 4.1------------------------------------
-- --[[
-- 	Actualiza una Knowledgebase contra el API AGREGANDO MetaData.
-- ]]--

-- local kbId = "8b281447-37c7-4e85-9d7f-b71f49970b55"
-- local vcc = "vcc1"

-- local updateInfo = {
-- 	kbId = kbId,
-- 	add = {}
-- }
-- table.insert(updateInfo.add, {
-- 		answer = "respuesta 2",
-- 		questions = {
-- 			"pregunta 2"
-- 		},
-- 		metadata = {
-- 			{name = "nombre", value = "Rocio"},
-- 			{name = "apellido", value = "de Mello"}
-- 		}
-- 	}
-- )
-- UpdateKnowledgeBase(updateInfo, vcc)

-- ---- TEST 4.2------------------------------------
-- --[[
-- 	Actualiza una Knowledgebase contra el API MODIFICANDO MetaData.
-- ]]--

-- local kbId = "8b281447-37c7-4e85-9d7f-b71f49970b55"
-- local vcc = "vcc1"

-- local updateInfo = {
-- 	kbId = kbId,
-- 	update = {}
-- }
-- table.insert(updateInfo.update, {
-- 		id = 1,
-- 		answer = "respuesta 4a",
-- 		questions = {
-- 			delete = {"pregunta 3a"},
-- 			add = {"pregunta 4a"}
-- 		},
-- 		metadata = {
-- 			delete = {
-- 			},
-- 			add = {
-- 				{name = "nombre", value = "Ellio"},
-- 				{name = "apellido", value = "Vallejo"}
-- 			--	{name = "nombre", value = "Rocio Ayelen"}
-- 			}
-- 			-- {name = "nombre", value = "Rocio Ayelen"},
-- 			-- {name = "apellido", value = "de Mello Aquino"}
-- 		}
-- 	}
-- )
-- UpdateKnowledgeBase(updateInfo, vcc)


---- TEST 4.3------------------------------------
--[[
	Actualiza una Knowledgebase contra el API MODIFICANDO MetaData.
]]--

-- local kbId = "8b281447-37c7-4e85-9d7f-b71f49970b55"
-- local vcc = "vcc1"

-- local updateInfo = {
-- 	kbId = kbId,
-- 	update = {}
-- }
-- table.insert(updateInfo.update, {
-- 		id = 17,
-- 		--answer = "respuesta 4a",
-- 		questions = {
-- 			delete = {},
-- 			add = {}
-- 		},
-- 		metadata = {
-- 			delete = {
-- 			},
-- 			add = {
-- 				{name = "ciudad", value = "Carmelo"}
-- 			}
-- 		}
-- 	}
-- )
-- UpdateKnowledgeBase(updateInfo, vcc)

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

---- TEST 5------------------------------------
--[[
	Publica una Knowledgebase contra el API.
]]--

-- local kbId = "8b281447-37c7-4e85-9d7f-b71f49970b55"
-- PublishKnowledgeBase(kbId, vcc)
---------------------------------------------------


---- TEST 6------------------------------------
--[[
	Obtiene información del detalle de la opración de la Knowledgebase contra el API.
]]--

-- local operationId = "c70600bd-a4b5-42cd-b701-8cb4170ba843"
-- GetKnowledgeBaseOperationDetails(operationId, vcc)
---------------------------------------------------


---- TEST 7------------------------------------
--[[
	Obtiene los Endpoint Keys de la Knowledgebase contra el API.
]]--

--GetKnowledgeBaseGetEndpointKeys(vcc)
---------------------------------------------------


-- ---- TEST 8------------------------------------
--[[
	Reemplaza una Knowledgebase contra el API.
]]--

-- local replaceInfo = {
	-- kbId = kbId,
	-- qnaList = {}
-- }
-- table.insert(replaceInfo.qnaList, {
		-- --id = 0,
		-- answer = "You can change the default message if you use the QnAMakerDialog. See this for details: https://docs.botframework.com/en-us/azure-bot-service/templates/qnamaker/#navtitle",
		-- -- source = "Editorial",
		-- questions = {
			-- "How can I change the default message from QnA Maker?"
		-- },
		-- -- metadata = {}
	-- }
-- )
-- ReplaceKnowledgeBase(replaceInfo, vcc)
-----------------------------------------------



---- TEST 9------------------------------------
--[[
	Obtiene las subscriptions que tiene asignadas un VCC (contra CASSANDRA)
]]--

--LoadVCCSubscriptions(vcc)

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


---- TEST 10 ------------------------------------
--[[
	Obtiene una subscription determinada que tiene asignada un VCC (contra CASSANDRA)
]]--

-- local subscriptionKey = "6c0aa9ff967b4833ad3018557272547e"
-- LoadVCCsBySubscription(subscriptionKey)
---------------------------------------------------


---- TEST 11 ------------------------------------
--[[
	Quita una subscription determinada de un VCC (contra CASSANDRA)
]]--

-- local subscriptionKey = "6c0aa9ff967b4833ad3018557272547e"
-- UnAssignSubscriptionKeyOfVCC(vcc, subscriptionKey)

-- local subscriptionKey = "867844dda8ac48a28d15cb31bce82c01"
-- UnAssignSubscriptionKeyOfVCC(vcc, subscriptionKey)

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


---- TEST 12 ------------------------------------
--[[
	Asigna una subscription determinada a un VCC (contra CASSANDRA)
]]--

-- local subscriptionKey = "6c0aa9ff967b4833ad3018557272547e"
-- AssignSubscriptionKeyToVCC({
	-- vcc = vcc,
	-- subscriptionKey = subscriptionKey,
	-- subscriptionName = "i6 PRIMERA"
-- })

-- local subscriptionKey = "867844dda8ac48a28d15cb31bce82c01"
-- AssignSubscriptionKeyToVCC({
	-- vcc = vcc,
	-- subscriptionKey = subscriptionKey,
	-- subscriptionName = "i6 SEGUNDA"
-- })

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


-- ---- TEST 13 ------------------------------------
--[[
	(RUNTIME - SSL) Realiza una pregunta contra el API para obtener una respuesta.
	Utiliza la rocka "SSL".
]]--

-- local vcc = "vcc1"
-- local info = {
-- 	question = "estacionamiento"
-- }
-- local mustUseCurl = false
-- GenerateAnswer(vcc, info, mustUseCurl)
-- print("")
-- print("")
-- -- ---- TEST 13.1 ------------------------------------
-- --[[
-- 	(RUNTIME - CURL) Realiza una pregunta contra el API para obtener una respuesta.
-- 	Utiliza "CURL".
-- ]]--

local vcc = "vcc1"
local info = {
	question = "estacionamiento",
	metadata = {
		filters = {
			{name = "ciudad", value = "colonia"},
		--	{name = "ciudad", value = "montevideo"}
		},
		--operationType = "AND"
	}
}
local mustUseCurl = true
GenerateAnswer(vcc, info, mustUseCurl)

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

-- ---- TEST 14 ------------------------------------
--[[
	(RUNTIME) Retorna información para poder realizar una pregutna contra el API.
	Retorna:
		{
		  "primaryEndpointKey": "b86abe85-a840-44bd-91c9-728892b2ea2e",
		  "resourceLocation": "/knowledgebases/4bd4560f-7288-4197-98de-e2403e0c8dfc",
		  "baseURI": "%s/qnamaker%s/generateAnswer",
		  "postData": {
			"question": ""
		  },
		  "headers": {
			"Authorization": "EndpointKey b86abe85-a840-44bd-91c9-728892b2ea2e"
		  },
		  "uri": "https://icqnamaker.azurewebsites.net/qnamaker/knowledgebases/4bd4560f-7288-4197-98de-e2403e0c8dfc/generateAnswer",
		  "hostName": "https://icqnamaker.azurewebsites.net"
		}

	Donde dentro de los atributos que debemos utilizar para armar el request son:
		"uri"
			Es la URL a la cual vamos a realizar el request.
		"headers"
			Es una tabla que contiene los headers de autorización que debemos añadir en el request.
		"postData"
			Contiene el formato del postData que debemos enviar.
			Tenemos que asignar al atributo "postData.question" el valor de nuestra pregunta.
]]--

--local vcc = "vcc1"
--GetAnswerPostInfo(vcc)
---------------------------------------------------


-- ---- TEST 14 ------------------------------------
--[[
	Elimina unicamente de CASSANDRA la knowledge base
]]--

-- local vcc = "borrame11"
-- RemoveKnowledgebaseOnlyCassandra(vcc)
---------------------------------------------------


