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 = "2.0" 

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 SIMPLE
-- -- *******************************************************************************

--[[
-----------------------------
MODELS - GET APPLICATION VERSION ENTITY INFOS
-----------------------------
	Gets information about the entity models.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/entities[?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
	------------
		[
		  {
			"id": "3d73462d-98f0-4dcd-8d30-fab9e65f2e73",
			"name": "DayOfWeek",
			"typeId": 1,
			"readableType": "Entity Extractor"
		  },
		  {
			"id": "b8e31be4-300f-455e-894b-6f079abca0a2",
			"name": "$Camera.AppName",
			"typeId": 1,
			"readableType": "Entity Extractor",
			"customPrebuiltDomainName": "Camera",
			"customPrebuiltModelName": "AppName"
		  }
		]

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

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

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

	LogInfo("[LUIS_ENTITIES_SIMPLE:LoadAllAppEntities] Success loaded all APP SIMPLE ENTITIES on appId '%s' versionId: '%s'.", appId, versionId)

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

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

	Request URL
	-----------------------------
		https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/entities/{entityId}

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

		versionId string The task version ID.

		entityId string Format - guid. The 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
	-----------------------------
		{
		  "id": "3d73462d-98f0-4dcd-8d30-fab9e65f2e73",
		  "name": "DayOfWeek",
		  "typeId": 1,
		  "readableType": "Entity Extractor"
		}


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

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

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

	LogInfo("[LUIS_ENTITIES_SIMPLE:GetAppEntity] Success get APP SIMPLE ENTITIES '%s' on appId '%s' versionId: '%s'.", entityId, appId, versionId)

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

--[[
-----------------------------
MODELS - CREATE ENTITY EXTRACTOR
-----------------------------
	Adds an entity extractor to the application.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/entities

	Request parameters
	------------
		appId string Format - guid. The application ID.
		versionId string The task version 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 name for the new entity extractor.
		application/json
		Sample
			{
				"name": "DayOfWeek"
			}

	Response 201
	------------
		The ID of the created model.

		"3d73462d-98f0-4dcd-8d30-fab9e65f2e73"

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5890b47c39e2bb17b84a55ff/operations/5890b47c39e2bb052c5b9c0e
]]--
function CreateAppEntity (info)
	assert(type(info) == "table")
	assert(info.appId)
	assert(info.versionId)

	local uri = MakeCompleteURI("APPS", "%s/versions/%s/entities", info.appId, info.versionId)

	local data = {
		name = info.name
	}
	local success, response = request.Post(uri, data)
	if not success then
		LogError("[LUIS_ENTITIES_SIMPLE:CreateAppEntity] Error creating APP SIMPLE ENTITIES on appId '%s' versionId: '%s'. Response: '%s'", info.appId, info.versionId, json.encode(response))
		return false, response
	end

	local entityId = table.concat(response)
	LogInfo("[LUIS_ENTITIES_SIMPLE:CreateAppEntity] Success created APP SIMPLE ENTITIES on appId '%s', entityId: '%s' versionId: '%s'.", info.appId, entityId, info.versionId)

	return true, entityId
end

--[[
-----------------------------
MODELS - RENAME ENTITY MODEL
-----------------------------
	Updates the name of an entity extractor.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/entities/{entityId}

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

		versionId string The task version ID.

		entityId string Format - guid. The 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.
		application/json
		Sample:
			{
				"name": "DaysOfWeek"
			}

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

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5890b47c39e2bb17b84a55ff/operations/5890b47c39e2bb052c5b9c1e
]]--
function RenameAppEntity (info)
	assert(info)
	assert(info.appId)
	assert(info.entityId)
	assert(info.versionId)
	assert(info.name)

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

	local data = {
		---- Requerido
		name = info.name
	}
	local success, response = request.Put(uri, data)
	if not success then
		LogError("[LUIS_ENTITIES_SIMPLE:RenameAppEntity] Error renaming APP SIMPLE 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_SIMPLE:RenameAppEntity] Success renamed APP SIMPLE ENTITIES '%s' on appId '%s' versionId: '%s'.", info.entityId, info.appId, info.versionId)

	return true, response
end

--[[
-----------------------------
MODELS - DELETE ENTITY MODEL
-----------------------------
	Deletes an entity extractor from the application.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/entities/{entityId}

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

		versionId string The task version ID.

		entityId string Format - guid. The 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

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

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

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

	LogInfo("[LUIS_ENTITIES_SIMPLE:DeleteAppEntity] Success deleted APP SIMPLE  ENTITIES '%s' versionId: '%s' on appId '%s'.", entityId, versionId, appId)

	return true, response
end
