local json = require "cjson"
local request = require "luis.request"

module(..., package.seeall)

local m_instanceOwner
function SetOwner (instanceOwner)
	m_instanceOwner = instanceOwner
end

local m_defaultAppVersion = "3.0-PREVIEW" 

local function MakeCompleteURI (uriBaseId, uri, ...)
	uriBaseId = uriBaseId or "APPS"
	return m_instanceOwner:MakeCompleteURI(m_defaultAppVersion, uriBaseId, uri, ...) 
end

--[[
	Retorna los parametros:
		1) Si tiene paginado    : "?skip=0&take=2"
		2) Si no tiene paginado : ""
]]--
local function MakePagingParameters (params)
	local api = require "luis"
	return api.MakePagingParameters(params)
end

-- *******************************************************************************
-- API ENTITIES HIERARCHICAL
-- -- *******************************************************************************

--[[
-----------------------------
MODELS - GET VERSION HIERARCHICAL ENTITY LIST
-----------------------------
	Gets information about the hierarchical entity models.

	Request URL
	------------
		https://[location].api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/hierarchicalentities[?skip][&take]

	Request parameters
	------------
		appId string Format - guid. The application ID.

		versionId string The task version ID.

		skip (optional) integer The number of entries to skip. Default value is 0.

		take (optional) integer The number of entries to return. Maximum page size is 500. Default is 100.

	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
	------------
		A list of hierarchical entity model infos.
		[
			{
				"id": "fe559c31-9778-42ea-ba45-94e0bd7cf767",
				"name": "Location",
				"typeId": 3,
				"readableType": "Hierarchical Entity Extractor",
				"children": [
					{
						"id": "ec076676-d8d9-42fa-a44e-87989c0a2f82",
						"name": "From"
					},
					{
						"id": "63ebd752-4e81-4ce7-a698-b59b82bf5519",
						"name": "To"
					}
				],
				"roles": [
					{
						"id": "eb64dfeb-b54a-4b8a-b2d5-9315beea055a",
						"name": "role 1"
					},
					{
						"id": "b3abd65c-d187-4bd0-9fd2-81cbd0dd2026",
						"name": "role 2"
					}
				]
			}
		]

	Response 429
	------------
		Rate limit is exceeded.

	Response 400
	------------
		This error can be returned if the request's parameters are incorrect meaning the required parameters are missing, malformed, or too large.

	Response 401
	------------
		You do not have access.

		Reasons can include:

		used endpoint subscription key, instead of authoring key
		invalid, malformed, or empty authoring key
		authoring key doesn't match region
		you are not the owner or collaborator
		invalid order of API calls

	Response 403
	------------
		Total monthly key quota limit exceeded

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5890b47c39e2bb17b84a55ff/operations/5890b47c39e2bb052c5b9c13
]]--
function LoadAllAppEntities (appId, versionId, paginated)
	assert(appId)
	assert(versionId)

	local uri = MakeCompleteURI("APPS", "%s/versions/%s/hierarchicalentities", appId, versionId)
	uri = uri .. MakePagingParameters(paginated)

	local success, response = request.Get(uri)
	if not success then
		LogError("[LUIS_ENTITIES_HIERARCHICAL.v3.0_PREVIEW:LoadAllAppEntities] Error loading all APP HIERARCHICAL ENTITIES on appId '%s' versionId: '%s'. Error: '%s'", appId, versionId, json.encode(response))
		return false, response
	end

	LogInfo("[LUIS_ENTITIES_HIERARCHICAL.v3.0_PREVIEW:LoadAllAppEntities] Success loaded all APP HIERARCHICAL ENTITIES on appId '%s' versionId: '%s'.", appId, versionId)

	local encodedEntities = table.concat(response)
	return true, encodedEntities
end


--[[
-----------------------------
MODELS - GET HIERARCHICAL ENTITY
-----------------------------
	Gets information about the hierarchical entity model.

	Request URL
	-----------------------------
		https://[location].api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}

	Request parameters
	-----------------------------
		appId string Format - guid. The application ID.

		versionId string The task version ID.

		hEntityId string Format - guid. The hierarchical entity extractor 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
	-----------------------------
	A hierarchical entity model info.
		{
			"id": "fe559c31-9778-42ea-ba45-94e0bd7cf767",
			"name": "Location",
			"typeId": 3,
			"readableType": "Hierarchical Entity Extractor",
			"children": [
				{
					"id": "ec076676-d8d9-42fa-a44e-87989c0a2f82",
					"name": "From"
				},
				{
					"id": "63ebd752-4e81-4ce7-a698-b59b82bf5519",
					"name": "To"
				}
			],
			"roles": [
				{
					"id": "eb64dfeb-b54a-4b8a-b2d5-9315beea055a",
					"name": "role 1"
				},
				{
					"id": "b3abd65c-d187-4bd0-9fd2-81cbd0dd2026",
					"name": "role 2"
				}
			]
		}

	Response 429
	------------
		Rate limit is exceeded.

	Response 400
	------------
		This error can be returned if the request's parameters are incorrect meaning the required parameters are missing, malformed, or too large.

	Response 401
	------------
		You do not have access.

		Reasons can include:
			used endpoint subscription key, instead of authoring key
			invalid, malformed, or empty authoring key
			authoring key doesn't match region
			you are not the owner or collaborator
			invalid order of API calls

	Response 403
	------------
		Total monthly key quota limit exceeded

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5890b47c39e2bb17b84a55ff/operations/5890b47c39e2bb052c5b9c20
]]--
function GetAppEntity (appId, entityId, versionId)
	assert(appId)
	assert(entityId)
	assert(versionId)

	local uri = MakeCompleteURI("APPS", "%s/versions/%s/hierarchicalentities/%s", appId, versionId, entityId)

	local success, response = request.Get(uri)
	if not success then
		LogError("[LUIS_ENTITIES_HIERARCHICAL.v3.0_PREVIEW:GetAppEntity] Error get APP HIERARCHICAL ENTITIES '%s' on appId '%s' versionId: '%s' Error: '%s'", entityId, appId, versionId, json.encode(response))
		return false, response
	end

	LogInfo("[LUIS_ENTITIES_HIERARCHICAL.v3.0_PREVIEW:GetAppEntity] Success get APP HIERARCHICAL ENTITIES '%s' on appId '%s' versionId: '%s'.", entityId, appId, versionId)

	local encodedEntity = table.concat(response)
	return true, encodedEntity
end

--[[
-----------------------------
MODELS - CREATE HIERARCHICAL ENTITY
-----------------------------
	Este metodo el API de la version 3.0 NO lo soporta.
]]--
function CreateAppEntity (info)
	local response = {
		response = {
			error = {
				message = "Method not supported in api 3.0 PREVIEW",
				code = "UNSUPPORTED METHOD"
			}
		},
		code = 404
	}
	LogError("[LUIS_ENTITIES_HIERARCHICAL.v3.0_PREVIEW:CreateAppEntity] Error creating APP HIERARCHICAL ENTITIES on appId '%s' versionId: '%s'. Response: '%s'", info.appId, info.versionId, json.encode(response))
	return false, response
end

--[[
-----------------------------
MODELS - UPDATE HIERARCHICAL ENTITY
-----------------------------
	Updates the name of a hierarchical entity model.

	Request URL
	------------
		https://{endpoint}/luis/authoring/v3.0-preview/apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}

	Request parameters
	------------
		appId string Format - guid. The application ID.

		versionId string The task version ID.

		hEntityId string Format - guid. The hierarchical entity extractor ID.

	Request headers
	------------
		Content-Type (optional) 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
	------------
		A model object containing the new entity extractor name and children.
		application/json
		Sample:
			{
				"name": "Location"
			}

	Response 200
	------------
		Empty response

	Response 429
	------------
		Rate limit is exceeded.

	Response 400
	------------
		This error can be returned if the request's parameters are incorrect meaning the required parameters are missing, malformed, or too large.
		This error can be returned if the request's body is incorrect meaning the JSON is missing, malformed, or too large.


	Response 401
	------------
		You do not have access.

		Reasons can include:

			used endpoint subscription key, instead of authoring key
			invalid, malformed, or empty authoring key
			authoring key doesn't match region
			you are not the owner or collaborator
			invalid order of API calls

	Response 403
	------------
		Total monthly key quota limit exceeded

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/luis-programmatic-apis-v3-0-preview/operations/5890b47c39e2bb052c5b9c21
]]--
function RenameAppEntity (info)
	assert(info)
	assert(info.appId)
	assert(info.entityId)
	assert(info.versionId)
	assert(info.entity)

	----------------------------------------------------------------------------
	-- Este el metodo Implementado segun el API 3.0
	---------------------------------------------------------------------------
	-- local uri = MakeCompleteURI("APPS", "%s/versions/%s/hierarchicalentities/%s", info.appId, info.versionId, info.entityId)

	-- local data = {
	-- 	---- Requerido
	-- 	name = info.entity.name
	-- }
	-- local success, response = request.Patch(uri, data)
	-- if not success then
	-- 	LogError("[LUIS_ENTITIES_HIERARCHICAL.v2.0:RenameAppEntity] Error renaming APP HIERARCHICAL ENTITIES '%s' on appId '%s' versionId: '%s'. Response: '%s'", info.entityId, info.appId, info.versionId, json.encode(response))
	-- 	return false, response
	-- end

	-- LogInfo("[LUIS_ENTITIES_HIERARCHICAL.v2.0:RenameAppEntity] Success renamed APP HIERARCHICAL ENTITIES '%s' on appId '%s' versionId: '%s'.", info.entityId, info.appId, info.versionId)

	-- return true, response

	----------------------------------------------------------------------------
	--[[
		Se invoca a la funcion del API 2.0 ya que desde la GUI esta realizando este invoke cruzado para eliminar hijos (solo eliminar)
		Lo mismo se realiza desde la interfaz de LUIS.
	]]--

	LogInfo("[LUIS_ENTITIES_HIERARCHICAL.v3.0_PREVIEW:RenameAppEntity] Invoke API 2.0 for Rename HIERARCHICAL ENTITIES '%s' on appId '%s' versionId: '%s'.", info.entityId, info.appId, info.versionId)

	local entitiesHierarchical2_0 = require "luis.v2_0.entitiesHierarchical"

	local success, response = entitiesHierarchical2_0.RenameAppEntity(info)
	return success, response
end

--[[
-----------------------------
MODELS - DELETE HIERARCHICAL ENTITY
-----------------------------
	Deletes a hierarchical entity extractor from the application version.

	Request URL
	------------
		https://[location].api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}

	Request parameters
	------------
		appId string Format - guid. The application ID.

		versionId string The task version ID.

		hEntityId string Format - guid. The hierarchical entity extractor 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
	------------
		Empty response

	Response 429
	------------
		Rate limit is exceeded.


	Response 400
	------------
		This error can be returned if the request's parameters are incorrect meaning the required parameters are missing or malformed.

	Response 401
	------------
		You do not have access.

		Reasons can include:
			used endpoint subscription key, instead of authoring key
			invalid, malformed, or empty authoring key
			authoring key doesn't match region
			you are not the owner or collaborator
			invalid order of API calls

	Response 403
	------------
		Total monthly key quota limit exceeded

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5890b47c39e2bb17b84a55ff/operations/5890b47c39e2bb052c5b9c22
]]--
function DeleteAppEntity (appId, entityId, versionId)
	assert(appId)
	assert(entityId)
	assert(versionId)

	local uri = MakeCompleteURI("APPS", "%s/versions/%s/hierarchicalentities/%s", appId, versionId, entityId)

	local success, response = request.Delete(uri)
	if not success then
		LogError("[LUIS_ENTITIES_HIERARCHICAL.v3.0_PREVIEW:DeleteAppEntity] Error deleting APP HIERARCHICAL ENTITIES '%s' versionId: '%s' on appId '%s'. Response: '%s'", entityId, versionId, appId, json.encode(response))
		return false, response
	end

	LogInfo("[LUIS_ENTITIES_HIERARCHICAL.v3.0_PREVIEW:DeleteAppEntity] Success deleted APP HIERARCHICAL ENTITIES '%s' versionId: '%s' on appId '%s'.", entityId, versionId, appId)

	return true, response
end
