local json = require "json"
local request = require "qna_maker.request"

module(..., package.seeall)

local function GetBaseURI (id)
	id = id or "KNOWLEDGEBASES"
	local api = require "qna_maker"
	return api.GetBaseURI(id)
end

local function MakeCompleteURI (uriBaseId, uri, ...)
	uriBaseId = uriBaseId or "KNOWLEDGEBASES"
	local api = require "qna_maker"
	return api.MakeCompleteURI(uriBaseId, uri, ...)
end

--[[
-----------------------------
KNOWLEDGEBASE - LOAD
-----------------------------
	Get Knowledgebases for user

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases

	Request headers
	------------
		Ocp-Apim-Subscription-Key string Subscription key which provides access to this API. Found in your Cognitive Services accounts.

	Request body
	------------
		...
	Response 200
	------------
		Collection of knowlegebases.
		{
		  "knowledgebases": [
			{
			  "id": "9d091697-fb8c-4ed5-9ac0-35bf8273bfff",
			  "hostName": "https://myqnamakerbot.azurewebsites.net",
			  "lastAccessedTimestamp": "2018-03-16T10:59:46Z",
			  "lastChangedTimestamp": "2018-03-16T10:58:10Z",
			  "lastPublishedTimestamp": "2018-03-16T10:59:56Z",
			  "name": "My QnA Maker Bot",
			  "userId": "03a4f4ce-30a6-4ec6-b436-02bcdf6153e1",
			  "urls": [
				"https://docs.microsoft.com/en-in/azure/cognitive-services/qnamaker/faqs",
				"https://docs.microsoft.com/en-us/bot-framework/resources-bot-framework-faq"
			  ],
			  "sources": [
				"Custom Editorial",
				"SurfaceManual.pdf"
			  ]
			}
		  ]
		}
	Response 400
	------------
		application/json
		{
		  "error": {
			"code": "BadArgument",
			"message": "Invalid input. See details.",
			"details": [
			  {
				"code": "ValidationFailure",
				"message": "'Name' should not be empty.",
				"target": "Name"
			  }
			]
		  }
		}
	Response 401
	------------
		application/json
		{
		  "error": {
			"code": "Unauthorized",
			"message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."
		  }
		}
	Response 403
	------------
		application/json
		{
		  "error": {
			"code": "Forbidden",
			"message": "You do not have permissions to view the requested resource."
		  }
		}
	Response 404
	------------
		application/json
		{
		  "error": {
			"code": "NotFound",
			"message": "The requested knowledge base is not found."
		  }
		}
	Response 500
	------------
		application/json
		{
		  "error": {
			"code": "Unspecified",
			"message": "Something happened. Please retry after some time."
		  }
		}

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5a93fcf85b4ccd136866eb37/operations/knowledgebases_getknowledgebasesforuser
]]--

function Load (ocpApimSubscriptionKey)
	assert(type(ocpApimSubscriptionKey) == "string")
	local uri = GetBaseURI()

	local success, response = request.Get(uri, ocpApimSubscriptionKey)
	if not success then
		LogError("[QNA_MAKER_KNOWLEDGEBASE:Load] Loading Knowledgebases. Error: '%s'", json.encode(response))
		return false, response
	end

	LogInfo("[QNA_MAKER_KNOWLEDGEBASE:Load] Success Loaded Knowledgebases.")

	local encodedKnowledgebases = table.concat(response)

	--LogDebug("[QNA_MAKER_KNOWLEDGEBASE:Load] Loaded Knowledgebases, data: '%s'", encodedKnowledgebases)
	return true, encodedKnowledgebases
end

--[[
-----------------------------
KNOWLEDGEBASE - DOWNLOAD
-----------------------------
	Download the knowledgebase.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases/{kbId}/{environment}/qna

	Request parameters
	------------
		kbId string Knowledgebase id
		environment string Specifies whether environment is Test or Prod.

	Request headers
	------------
		Ocp-Apim-Subscription-Key string Subscription key which provides access to this API. Found in your Cognitive Services accounts.

	Request body
	------------
		...
	Response 200
	------------
		Collection of all Q-A in the knowledgebase.
		{
		  "qnaDocuments": [
			{
			  "id": 1,
			  "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": "Custom Editorial",
			  "questions": [
				"How can I change the default message from QnA Maker?"
			  ],
			  "metadata": []
			},
			{
			  "id": 2,
			  "answer": "You can use our REST apis to manage your KB. See here for details: https://westus.dev.cognitive.microsoft.com/docs/services/58994a073d9e04097c7ba6fe/operations/58994a073d9e041ad42d9baa",
			  "source": "Custom Editorial",
			  "questions": [
				"How do I programmatically update my KB?"
			  ],
			  "metadata": [
				{
				  "name": "category",
				  "value": "api"
				}
			  ]
			},
		  ]
		}

	Response 400
	------------
		application/json
		{
		  "error": {
			"code": "BadArgument",
			"message": "Invalid input. See details.",
			"details": [
			  {
				"code": "ValidationFailure",
				"message": "'Name' should not be empty.",
				"target": "Name"
			  }
			]
		  }
		}
	Response 401
	------------
		application/json
		{
		  "error": {
			"code": "Unauthorized",
			"message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."
		  }
		}
	Response 403
	------------
		application/json
		{
		  "error": {
			"code": "Forbidden",
			"message": "You do not have permissions to view the requested resource."
		  }
		}
	Response 404
	------------
		application/json
		{
		  "error": {
			"code": "NotFound",
			"message": "The requested knowledge base is not found."
		  }
		}
	Response 500
	------------
		application/json
		{
		  "error": {
			"code": "Unspecified",
			"message": "Something happened. Please retry after some time."
		  }
		}

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5a93fcf85b4ccd136866eb37/operations/knowledgebases_download
]]--

function Download (kbId, environment, ocpApimSubscriptionKey)
	assert(type(ocpApimSubscriptionKey) == "string")
	assert(type(kbId) == "string")
	assert(type(environment) == "string")

	local uri = MakeCompleteURI("KNOWLEDGEBASES", "%s/%s/qna", kbId, environment) --/{kbId}/{environment}/qna

	local success, response = request.Get(uri, ocpApimSubscriptionKey)
	if not success then
		LogError("[QNA_MAKER_KNOWLEDGEBASE:Download] Downloading Knowledgebase. Error: '%s'", json.encode(response))
		return false, response
	end

	LogInfo("[QNA_MAKER_KNOWLEDGEBASE:Download] Success Downloaded Knowledgebase.")

	local encodedKnowledgebase = table.concat(response)

	--LogDebug("[QNA_MAKER_KNOWLEDGEBASE:Download] Downloaded Knowledgebase, data: '%s'", encodedKnowledgebase)
	return true, encodedKnowledgebase
end

--[[
-----------------------------
KNOWLEDGEBASE - CREATE
-----------------------------
	Create Knowledgebase
		Asynchronous operation to create a new knowledgebase.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases/create

	Request headers
	------------
		Content-Type string Media type of the body sent to the API.
		Ocp-Apim-Subscription-Key string Subscription key which provides access to this API. Found in your Cognitive Services accounts.

	Request body
	------------
		Post body of the request.

		Using Metadata

		Metadata lets you add additional information to your QnAs, as key/value pairs. This information can be used in various ways like filtering results, boost results, store additional information which can be used in the followup conversations, etc.

		QnA Entity

		Before we see an example of how to use metadata, it's important to understand how we store the QnA data. The QnA entity now looks like below:

		Each QnA entity is uniquely identified by a qnaId which is persistent. The qnaId can be used to make any updates to a particular QnA entity.

		application/json

		Sample:
			{
			  "name": "QnA Maker FAQ",
			  "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": "Custom Editorial",
				  "questions": [
					"How can I change the default message from QnA Maker?"
				  ],
				  "metadata": []
				},
				{
				  "id": 0,
				  "answer": "You can use our REST apis to manage your KB. See here for details: https://westus.dev.cognitive.microsoft.com/docs/services/58994a073d9e04097c7ba6fe/operations/58994a073d9e041ad42d9baa",
				  "source": "Custom Editorial",
				  "questions": [
					"How do I programmatically update my KB?"
				  ],
				  "metadata": [
					{
					  "name": "category",
					  "value": "api"
					}
				  ]
				}
			  ],
			  "urls": [
				"https://docs.microsoft.com/en-in/azure/cognitive-services/qnamaker/faqs",
				"https://docs.microsoft.com/en-us/bot-framework/resources-bot-framework-faq"
			  ],
			  "files": [
				{
				  "fileName": "SurfaceManual.pdf",
				  "fileUri": "https://download.microsoft.com/download/2/9/B/29B20383-302C-4517-A006-B0186F04BE28/surface-pro-4-user-guide-EN.pdf"
				}
			  ]
			}

	Response 202
	------------
		Details of the asynchronous operation.

		application/json
		{
		  "operationState": "NotStarted",
		  "createdTimestamp": "2018-03-19T07:38:46Z",
		  "lastActionTimestamp": "2018-03-19T07:39:29Z",
		  "userId": "86bb8390-56c0-42c2-9f81-3de161981191",
		  "operationId": "03a4f4ce-30a6-4ec6-b436-02bcdf6153e1"
		}
	Response 400
	------------
		application/json
		{
		  "error": {
			"code": "BadArgument",
			"message": "Invalid input. See details.",
			"details": [
			  {
				"code": "ValidationFailure",
				"message": "'Name' should not be empty.",
				"target": "Name"
			  }
			]
		  }
		}
	Response 401
	------------
		application/json
		{
		  "error": {
			"code": "Unauthorized",
			"message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."
		  }
		}
	Response 403
	------------
		application/json
		{
		  "error": {
			"code": "Forbidden",
			"message": "You do not have permissions to view the requested resource."
		  }
		}
	Response 404
	------------
		application/json
		{
		  "error": {
			"code": "NotFound",
			"message": "The requested knowledge base is not found."
		  }
		}
	Response 500
	------------
		application/json
		{
		  "error": {
			"code": "Unspecified",
			"message": "Something happened. Please retry after some time."
		  }
		}

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5a93fcf85b4ccd136866eb37/operations/5ac266295b4ccd1554da75ff

	SAMPLE i6 Basic POST data:
		{"name":"test_emma1","enableHierarchicalExtraction":false,"hostUrl":""}
]]--
function Create (info, ocpApimSubscriptionKey)
	assert(type(ocpApimSubscriptionKey) == "string")
	assert(type(info) == "table")
	assert(type(info.name) == "string")

	local uri = MakeCompleteURI("KNOWLEDGEBASES", "create")

	local data = {
		-- Requerido
		name                         = info.name,
		--  Opcionales
		enableHierarchicalExtraction = info.enableHierarchicalExtraction or false,
		hostUrl                      = info.hostUrl or "",
		files                        = info.files or nil,
		urls                         = info.urls or nil,
		users                        = info.users or nil,
		qnaList                      = info.qnaList or nil
	}
	local contentType = nil
	local success, response = request.Post(uri, data, contentType, ocpApimSubscriptionKey)
	if not success then
		LogError("[QNA_MAKER_KNOWLEDGEBASE:Create] Creating knowledgeBase name '%s'. Error: '%s'", info.name, json.encode(response))
		return false, response
	end

	local encodedResponse = table.concat(response)
	LogInfo("[QNA_MAKER_KNOWLEDGEBASE:Create] Success created knowledgeBase name '%s'. Response: '%s'.", info.name, encodedResponse)

	response = json.decode(encodedResponse)

	return true, response
end

--[[
-----------------------------
KNOWLEDGEBASE - UPDATE
-----------------------------
	Update Knowledgebase
	Asynchronous operation to modify a knowledgebase.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases/{kbId}

	Request parameters
	------------
		kbId string Knowledgebase id.

	Request headers
	------------
		Content-Type string Media type of the body sent to the API.
		Ocp-Apim-Subscription-Key string Subscription key which provides access to this API. Found in your Cognitive Services accounts.

	Request body
	------------
		Post body of the request.

		Using Metadata

		Metadata lets you add additional information to your QnAs, as key/value pairs. This information can be used in various ways like filtering results, boost results, store additional information which can be used in the followup conversations, etc.

		QnA Entity

		Before we see an example of how to use metadata, it's important to understand how we store the QnA data. The QnA entity now looks like below:

		Each QnA entity is uniquely identified by a qnaId which is persistent. The qnaId can be used to make any updates to a particular QnA entity.

		application/json

		Sample:
			{
			  "add": {
				"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": "Custom Editorial",
					"questions": [
					  "How can I change the default message from QnA Maker?"
					],
					"metadata": []
				  },
				  {
					"id": 0,
					"answer": "You can use our REST apis to manage your KB. See here for details: https://westus.dev.cognitive.microsoft.com/docs/services/58994a073d9e04097c7ba6fe/operations/58994a073d9e041ad42d9baa",
					"source": "Custom Editorial",
					"questions": [
					  "How do I programmatically update my KB?"
					],
					"metadata": [
					  {
						"name": "category",
						"value": "api"
					  }
					]
				  }
				],
				"urls": [
				  "https://docs.microsoft.com/en-us/azure/cognitive-services/Emotion/FAQ"
				],
				"files": [
				  {
					"fileName": "SurfaceManual.pdf",
					"fileUri": "https://download.microsoft.com/download/2/9/B/29B20383-302C-4517-A006-B0186F04BE28/surface-pro-4-user-guide-EN.pdf"
				  }
				]
			  },
			  "delete": {
				"ids": [
				  4,
				  13,
				  35
				],
				"sources": [
				  "Custom Editorial"
				]
			  },
			  "update": {
				"name": "QnA Maker + Emotion API FAQ Bot",
				"qnaList": [
				  {
					"id": 30,
					"answer": "Yes, you can use our REST APIs to manage a KB. Please check our documentation for details.",
					"source": "Custom Q&A",
					"questions": {
					  "add": [
						"can I programmatically manage a KB?"
					  ],
					  "delete": [
						"How do I programmatically update my KB?"
					  ]
					},
					"metadata": {
					  "delete": [
						{
						  "name": "category",
						  "value": "api"
						}
					  ],
					  "add": [
						{
						  "name": "category",
						  "value": "programmatic"
						}
					  ]
					}
				  }
				],
				"urls": [
				  "https://docs.microsoft.com/en-us/bot-framework/resources-bot-framework-faq"
				]
			  }
			}

	Response 202
	------------
		Details of the asynchronous operation.

		application/json
		{
		  "operationState": "NotStarted",
		  "createdTimestamp": "2018-03-19T07:38:46Z",
		  "lastActionTimestamp": "2018-03-19T07:39:29Z",
		  "userId": "86bb8390-56c0-42c2-9f81-3de161981191",
		  "operationId": "03a4f4ce-30a6-4ec6-b436-02bcdf6153e1"
		}
	Response 400
	------------
		application/json
		{
		  "error": {
			"code": "BadArgument",
			"message": "Invalid input. See details.",
			"details": [
			  {
				"code": "ValidationFailure",
				"message": "'Name' should not be empty.",
				"target": "Name"
			  }
			]
		  }
		}
	Response 401
	------------
		application/json
		{
		  "error": {
			"code": "Unauthorized",
			"message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."
		  }
		}
	Response 403
	------------
		application/json
		{
		  "error": {
			"code": "Forbidden",
			"message": "You do not have permissions to view the requested resource."
		  }
		}
	Response 404
	------------
		application/json
		{
		  "error": {
			"code": "NotFound",
			"message": "The requested knowledge base is not found."
		  }
		}
	Response 500
	------------
		application/json
		{
		  "error": {
			"code": "Unspecified",
			"message": "Something happened. Please retry after some time."
		  }
		}

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5a93fcf85b4ccd136866eb37/operations/5ac266295b4ccd1554da7600

	SAMPLE i6 Basic POST data:
		{
		  "add": {
			"qnaList": [
			  {
				"answer": "ellio",
				"source": "Editorial",
				"questions": [
				  "tu nombre"
				],
				"metadata": [],
				"context": {
				  "isContextOnly": false,
				  "prompts": []
				}
			  }
			]
		  },
		  "delete": {
			"ids": []
		  },
		  "update": {
			"qnaList": []
		  }
		}
]]--

function Update (info, ocpApimSubscriptionKey)
	assert(type(ocpApimSubscriptionKey) == "string")
	assert(type(info) == "table")
	assert(type(info.kbId) == "string")
	assert(type(info.add) == "table")
	assert(type(info.delete) == "table")
	assert(type(info.update) == "table")

	local kbId = info.kbId
	local uri = MakeCompleteURI("KNOWLEDGEBASES", "%s", kbId)

	local data = {
		add = {
			qnaList = info.add.qnaList
		},
		-- delete = {
			-- ids = info.delete.ids
		-- },
		-- update = {
			-- name = info.name,
			-- -- qnaList = info.update.qnaList
		-- }
	}

	if info.delete.ids then
		data.delete = {}
		data.delete.ids = info.delete.ids
	end

	if info.update then
		data.update = {}
		data.update.name = info.update.name
	end
	if info.update and info.update.qnaList then
		data.update = data.update or {}
		data.update.qnaList = info.update.qnaList
	end

	--LogDebug("3--------> %s", json.encode(data))

-- data = '{"add":{"qnaList":[{"answer":"respuesta1","source":"Editorial","questions":["pregunta1"],"metadata":[],"context":{"isContextOnly":false,"prompts":[]}}]},"delete":{"ids":[]},"update":{"qnaList":[]}}'
-- LogDebug("---> %s", data)
-- data = json.decode(data)

	local contentType = nil
	local success, response = request.Patch(uri, data, contentType, ocpApimSubscriptionKey)
	if not success then
		LogError("[QNA_MAKER_KNOWLEDGEBASE:Update] Updating knowledgeBase kbId '%s'. Error: '%s'", kbId, json.encode(response))
		return false, response
	end

	local encodedResponse = table.concat(response)
	LogInfo("[QNA_MAKER_KNOWLEDGEBASE:Update] Success updated knowledgeBase kbId '%s'. Response: '%s'.", kbId, encodedResponse)

	response = json.decode(encodedResponse)

	return true, response
end

--[[
-----------------------------
KNOWLEDGEBASE - REPLACE
-----------------------------
	Replace Knowledgebase
		Replace knowledgebase contents.

	Request parameters
	------------
		...

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases/{kbId}

	Request headers
	------------
		Content-Type string Media type of the body sent to the API.
		Ocp-Apim-Subscription-Key string Subscription key which provides access to this API. Found in your Cognitive Services accounts.

	Request body
	------------
		An instance of ReplaceKbDTO which contains list of qnas to be uploaded

		application/json
			{
			  "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": "Custom Editorial",
				  "questions": [
					"How can I change the default message from QnA Maker?"
				  ],
				  "metadata": []
				},
				{
				  "id": 0,
				  "answer": "You can use our REST apis to manage your KB. See here for details: https://westus.dev.cognitive.microsoft.com/docs/services/58994a073d9e04097c7ba6fe/operations/58994a073d9e041ad42d9baa",
				  "source": "Custom Editorial",
				  "questions": [
					"How do I programmatically update my KB?"
				  ],
				  "metadata": [
					{
					  "name": "category",
					  "value": "api"
					}
				  ]
				}
			  ]
			}

	Response 204
	------------
		HTTP 204 No content.

		}
	Response 400
	------------
		application/json
		{
		  "error": {
			"code": "BadArgument",
			"message": "Invalid input. See details.",
			"details": [
			  {
				"code": "ValidationFailure",
				"message": "'Name' should not be empty.",
				"target": "Name"
			  }
			]
		  }
		}
	Response 401
	------------
		application/json
		{
		  "error": {
			"code": "Unauthorized",
			"message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."
		  }
		}
	Response 403
	------------
		application/json
		{
		  "error": {
			"code": "Forbidden",
			"message": "You do not have permissions to view the requested resource."
		  }
		}
	Response 404
	------------
		application/json
		{
		  "error": {
			"code": "NotFound",
			"message": "The requested knowledge base is not found."
		  }
		}
	Response 500
	------------
		application/json
		{
		  "error": {
			"code": "Unspecified",
			"message": "Something happened. Please retry after some time."
		  }
		}

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5a93fcf85b4ccd136866eb37/operations/5ac266295b4ccd1554da75fe
]]--
function Replace (info, ocpApimSubscriptionKey)
	assert(type(ocpApimSubscriptionKey) == "string")
	assert(type(info) == "table")
	assert(type(info.kbId) == "string")
	assert(type(info.qnaList) == "table")

	local kbId = info.kbId
	local uri = MakeCompleteURI("KNOWLEDGEBASES", "%s", kbId)

	local data = {
		qnaList = info.qnaList
	}

	local contentType = nil
	local success, response = request.Put(uri, data, contentType, ocpApimSubscriptionKey)
	if not success then
		LogError("[QNA_MAKER_KNOWLEDGEBASE:Replace] Replacing knowledgeBase kbId '%s'. Error: '%s'", kbId, json.encode(response))
		return false, response
	end

	response = table.concat(response)
	LogInfo("[QNA_MAKER_KNOWLEDGEBASE:Replace] Success Replaced knowledgeBase kbId '%s'. Response: '%s'.", kbId, response)

	return true, response
end

--[[
-----------------------------
KNOWLEDGEBASE - DELETE
-----------------------------
	Deletes the knowledgebase and all its data.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases/{kbId}

	Request parameters
	------------
		kbId string Knowledgebase id.

	Request headers
	------------
		Ocp-Apim-Subscription-Key string Subscription key which provides access to this API. Found in your Cognitive Services accounts.

	Request body
	------------
		...
	Response 204
	------------
		HTTP 204 No content.

	Response 400
	------------
		application/json
		{
		  "error": {
			"code": "BadArgument",
			"message": "Invalid input. See details.",
			"details": [
			  {
				"code": "ValidationFailure",
				"message": "'Name' should not be empty.",
				"target": "Name"
			  }
			]
		  }
		}
	Response 401
	------------
		application/json
		{
		  "error": {
			"code": "Unauthorized",
			"message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."
		  }
		}
	Response 403
	------------
		application/json
		{
		  "error": {
			"code": "Forbidden",
			"message": "You do not have permissions to view the requested resource."
		  }
		}
	Response 404
	------------
		application/json
		{
		  "error": {
			"code": "NotFound",
			"message": "The requested knowledge base is not found."
		  }
		}
	Response 500
	------------
		application/json
		{
		  "error": {
			"code": "Unspecified",
			"message": "Something happened. Please retry after some time."
		  }
		}

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5890b47c39e2bb17b84a55ff/operations/5890b47c39e2bb052c5b9c39
]]--
function Delete (kbId, ocpApimSubscriptionKey)
	assert(type(ocpApimSubscriptionKey) == "string")
	assert(kbId)

	local uri = MakeCompleteURI("KNOWLEDGEBASES", "%s", kbId)

	local contentType = nil
	local data = nil
	local success, response = request.Delete(uri, data, contentType, ocpApimSubscriptionKey)

	if not success then
		--[[
			En el caso de que la KNOWLEDGEBASES haya sido eliminada por fuera de INCONCERT, es decir que se haya eliminado desde la GUI de QnA Maker,
			el API de QnA Maker va retornar el código de error 400, y la descripción del porqué ha fallado.
			Como este código de error 400 puede llegar en diferentes tipos de error, hay que validar contra el código de error + la descripción del error.
			En el caso de que efectivamente la KNOWLEDGEBASES haya sido eliminada por fuera de INCONCERT, debemos retornar un código success, para que la función que ha invocado a la función actual, elimine de Cassandra el registro correspondiente a la KNOWLEDGEBASES.
		]]--
		if response and tostring(response.code) == "400" and (response.response and response.response.error) then
			local qnaMakerErrorMessage = (response.response.error.message or ""):lower()
			--LogDebug("[QNA_MAKER_KNOWLEDGEBASE:Delete] 1 - qnaMakerErrorMessage: '%s'", qnaMakerErrorMessage)
			local cannotFindError = ("Cannot find an KNOWLEDGEBASE with the ID %s."):format(kbId):lower()
			--LogDebug("[QNA_MAKER_KNOWLEDGEBASE:Delete] 2 - cannotFindError: '%s'", cannotFindError)
			if cannotFindError == qnaMakerErrorMessage then
				LogInfo("[QNA_MAKER_KNOWLEDGEBASE:Delete] KNOWLEDGEBASES '%s' does not exist in the QnA Maker Database. Response: '%s'.", kbId, json.encode(response))
				success = true
				-- Este el JSON que retorna el API de QnA Maker, cuando se ha eliminado correctamente la KNOWLEDGEBASES.
				-- Lo que hacemos acá, es retornar el mismo JSON hacia la función que me ha invocado, para que esta proceda.
				response = {code = "Success", message = "Operation Successful"}
				return true, response
			end
		end
		LogError("[QNA_MAKER_KNOWLEDGEBASE:Delete] Deleting KNOWLEDGEBASES '%s' Error: '%s'", kbId, json.encode(response))
		return false, response
	end

	LogInfo("[QNA_MAKER_KNOWLEDGEBASE:Delete] Success deleted KNOWLEDGEBASES %s.", kbId)

	--LogDebug("[QNA_MAKER_KNOWLEDGEBASE:Delete] response: '%s'", json.encode(response))
	return true, response
end

--[[
-----------------------------
KNOWLEDGEBASE - GET DETAIL
-----------------------------
	Gets details of a specific knowledgebase.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases/{kbId}

	Request parameters
	------------
		kbId string Knowledgebase id.

	Request headers
	------------
		Ocp-Apim-Subscription-Key string Subscription key which provides access to this API. Found in your Cognitive Services accounts.

	Request body
	------------
		...
	Response 200
	------------
		Details of the knowledgebase.
		application/json
			{
			  "id": "9d091697-fb8c-4ed5-9ac0-35bf8273bfff",
			  "hostName": "https://myqnamakerbot.azurewebsites.net",
			  "lastAccessedTimestamp": "2018-03-16T10:59:46Z",
			  "lastChangedTimestamp": "2018-03-16T10:58:10Z",
			  "lastPublishedTimestamp": "2018-03-16T10:59:56Z",
			  "name": "My QnA Maker Bot",
			  "userId": "03a4f4ce-30a6-4ec6-b436-02bcdf6153e1",
			  "urls": [
				"https://docs.microsoft.com/en-in/azure/cognitive-services/qnamaker/faqs",
				"https://docs.microsoft.com/en-us/bot-framework/resources-bot-framework-faq"
			  ],
			  "sources": [
				"Custom Editorial",
				"SurfaceManual.pdf"
			  ]
			}

	Response 400
	------------
		application/json
		{
		  "error": {
			"code": "BadArgument",
			"message": "Invalid input. See details.",
			"details": [
			  {
				"code": "ValidationFailure",
				"message": "'Name' should not be empty.",
				"target": "Name"
			  }
			]
		  }
		}
	Response 401
	------------
		application/json
		{
		  "error": {
			"code": "Unauthorized",
			"message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."
		  }
		}
	Response 403
	------------
		application/json
		{
		  "error": {
			"code": "Forbidden",
			"message": "You do not have permissions to view the requested resource."
		  }
		}
	Response 404
	------------
		application/json
		{
		  "error": {
			"code": "NotFound",
			"message": "The requested knowledge base is not found."
		  }
		}
	Response 500
	------------
		application/json
		{
		  "error": {
			"code": "Unspecified",
			"message": "Something happened. Please retry after some time."
		  }
		}

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5a93fcf85b4ccd136866eb37/operations/knowledgebases_getknowledgebasedetails
]]--
function GetDetail (kbId, ocpApimSubscriptionKey)
	assert(type(ocpApimSubscriptionKey) == "string")
	assert(kbId)

	local uri = MakeCompleteURI("KNOWLEDGEBASES", "%s", kbId)
	local success, response = request.Get(uri, ocpApimSubscriptionKey)

	if not success then
		LogError("[QNA_MAKER_KNOWLEDGEBASE:GetDetail] Retrieving '%s' Knowledgebase detail. Error: '%s'", kbId, json.encode(response))
		return false, response
	end

	LogInfo("[QNA_MAKER_KNOWLEDGEBASE:GetDetail] Success Retrieved '%s' Knowledgebase detail.", kbId)

	local encodedKnowledgebaseDetail = table.concat(response)

	--LogDebug("[QNA_MAKER_KNOWLEDGEBASE:GetDetail] Retrieved Knowledgebase detail, data: '%s'", encodedKnowledgebaseDetail)
	return true, encodedKnowledgebaseDetail
end



--[[
-----------------------------
KNOWLEDGEBASE - PUBLISH
-----------------------------
	Publish Knowledgebase
		Publishes all changes in test index of a knowledgebase to its prod index.

	Request parameters
	------------
		kbId string Knowledgebase id

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases/{kbId}

	Request headers
	------------
		Ocp-Apim-Subscription-Key string Subscription key which provides access to this API. Found in your Cognitive Services accounts.

	Request body
	------------
		...

	Response 204
	------------
		HTTP 204 No content.

		}
	Response 400
	------------
		application/json
		{
		  "error": {
			"code": "BadArgument",
			"message": "Invalid input. See details.",
			"details": [
			  {
				"code": "ValidationFailure",
				"message": "'Name' should not be empty.",
				"target": "Name"
			  }
			]
		  }
		}
	Response 401
	------------
		application/json
		{
		  "error": {
			"code": "Unauthorized",
			"message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."
		  }
		}
	Response 403
	------------
		application/json
		{
		  "error": {
			"code": "Forbidden",
			"message": "You do not have permissions to view the requested resource."
		  }
		}
	Response 404
	------------
		application/json
		{
		  "error": {
			"code": "NotFound",
			"message": "The requested knowledge base is not found."
		  }
		}
	Response 500
	------------
		application/json
		{
		  "error": {
			"code": "Unspecified",
			"message": "Something happened. Please retry after some time."
		  }
		}

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5a93fcf85b4ccd136866eb37/operations/5ac266295b4ccd1554da75fe
]]--
function Publish (kbId, ocpApimSubscriptionKey)
	assert(type(ocpApimSubscriptionKey) == "string")
	assert(type(kbId) == "string")

	local uri = MakeCompleteURI("KNOWLEDGEBASES", "%s", kbId)
	local contentType = nil
	local data = {}
	local success, response = request.Post(uri, data, contentType, ocpApimSubscriptionKey)

	if not success then
		LogError("[QNA_MAKER_KNOWLEDGEBASE:Publish] Publishing knowledgeBase kbId '%s'. Error: '%s'", kbId, json.encode(response))
		return false, response
	end

	response = table.concat(response)
	LogInfo("[QNA_MAKER_KNOWLEDGEBASE:Publish] Success Published knowledgeBase kbId '%s'. Response: '%s'.", kbId, response)

	return true, response
end