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

--[[
-----------------------------
FEATURES - GET APPLICATION VERSION FEATURES
-----------------------------
Gets all application version features.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/features[?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 JSON object containing a list of all phraselist features and a list of all pattern featuers in the application.

			{
			  "phraselistFeatures": [
				{
				  "id": 5341,
				  "name": "Cities",
				  "phrases": "Seattle,New York,Paris,Moscow,Beijin",
				  "isExchangeable": true,
				  "isActive": true
				},
				{
				  "id": 74598,
				  "name": "DaysOfWeek",
				  "phrases": "monday,tuesday,wednesday,thursday,friday,saturday,sunday",
				  "isExchangeable": true,
				  "isActive": true
				}
			  ],
			  "patternFeatures": [
				{
				  "id": 81231,
				  "name": "EmailPattern",
				  "pattern": "\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b",
				  "isActive": true
				}
			  ]
			}

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

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

	local success, response = request.Get(uri)
	if not success then
		LogError("[LUIS_FEATURES:LoadAllAppFeatures] Error loading FEATURES on appId '%s' versionId: '%s'. Error: '%s'", appId, versionId, json.encode(response))
		return false, response
	end

	LogInfo("[LUIS_FEATURES:LoadAllAppFeatures] Success loaded FEATURES on appId '%s' versionId: '%s'.", appId, versionId)

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

--[[
-----------------------------
FEATURES - GET APPLICATION VERSION PHRASELIST FEATURES
-----------------------------
Gets all application phraselist features.

	Request URL
	------------
		https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/{appId}/versions/{versionId}/phraselists[?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 JSON object containing a list of all phraselist features.
			[
			  {
				"id": 321421,
				"name": "Cities",
				"phrases": "Seattle,New York,Paris,Moscow,Beijin",
				"isExchangeable": true,
				"isActive": true
			  },
			  {
				"id": 97832,
				"name": "DaysOfWeek",
				"phrases": "monday,tuesday,wednesday,thursday,friday,saturday,sunday",
				"isExchangeable": true,
				"isActive": true
			  }
			]

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

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

	local success, response = request.Get(uri)
	if not success then
		LogError("[LUIS_FEATURES:LoadAllAppFeaturesPhraselist] Error loading FEATURES PHRASELIST on appId '%s' versionId: '%s'. Error: '%s'", appId, versionId, json.encode(response))
		return false, response
	end

	LogInfo("[LUIS_FEATURES:LoadAllAppFeaturesPhraselist] Success loaded FEATURES PHRASELIST on appId '%s' versionId: '%s'.", appId, versionId)

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

--[[
-----------------------------
FEATURES - CREATE PHRASELIST FEATURE
-----------------------------
Creates a new phraselist feature.

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

	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 JSON object containing Name, comma-separated Phrases and the isExchangeable boolean. Default value for isExchangeable is true.
		application/json
		Sample
			{
				"name": "DaysOfWeek",
				"phrases": "monday,tuesday,wednesday,thursday,friday,saturday,sunday",
				"isExchangeable": true
			}

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

		1823

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

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

	local data = {
		name = info.name,
		phrases = info.phrases,
		isActive = info.isActive,
		isExchangeable = info.isExchangeable
	}
	local success, response = request.Post(uri, data)
	if not success then
		LogError("[LUIS_FEATURES:CreatePhraselist] Error creating FEATURES PHRASELIST on appId '%s' versionId: '%s'. Response: '%s'", info.appId, info.versionId, json.encode(response))
		return false, response
	end

	local phraseId = table.concat(response)
	LogInfo("[LUIS_FEATURES:CreatePhraselist] Success created FEATURES PHRASELIST on appId '%s', phraseId: '%s' versionId: '%s'.", info.appId, phraseId, info.versionId)

	return true, phraseId
end

--[[
-----------------------------
FEATURES - UPDATE PHRASELIST FEATURE
-----------------------------
Updates the phrases, the state and the name of the phraselist feature.

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

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

		versionId string The version ID of the task.

		phraselistId integer The ID of the feature to be updated.

	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 JSON object containing either:
		1- Just a boolean called IsActive, in which case the status of the feature will be changed.
		2- Name, Pattern, Mode, and a boolean called IsActive to update the feature.

		application/json
		Sample:
			{
				"name": "BusinessDaysOfWeek",
				"phrases": "monday,tuesday,wednesday,thursday,friday"
			}

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

	Referencia: https://westus.dev.cognitive.microsoft.com/docs/services/5890b47c39e2bb17b84a55ff/operations/5890b47c39e2bb052c5b9c06
]]--
function UpdatePhraselist (info)
	assert(info)
	assert(info.appId)
	assert(info.phraseListId)
	assert(info.versionId)
	assert(info.name)
	assert(info.phrases)

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

	local data = {
		name = info.name,
		phrases = info.phrases,
		isActive = info.isActive,
		isExchangeable = info.isExchangeable
	}
	local success, response = request.Put(uri, data)
	if not success then
		LogError("[LUIS_FEATURES:UpdatePhraselist] Error updating FEATURES PHRASELIST '%s' on appId '%s' versionId: '%s'. Response: '%s'", info.phraseListId, info.appId, info.versionId, json.encode(response))
		return false, response
	end

	LogInfo("[LUIS_FEATURES:UpdatePhraselist] Success updated FEATURES PHRASELIST '%s' on appId '%s' versionId: '%s'.", info.phraseListId, info.appId, info.versionId)

	return true, response
end

--[[
-----------------------------
FEATURES - DELETE PHRASELIST FEATURE
-----------------------------
Deletes a phraselist feature from an application.

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

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

		versionId string The task version ID.

		phraselistId integer The ID of the feature to be deleted.

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


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

	local uri = MakeCompleteURI("APPS", "%s/versions/%s/phraselists/%s", appId, versionId, phraseListId)

	local success, response = request.Delete(uri)
	if not success then
		LogError("[LUIS_FEATURES:DeletePhraselist] Error deleting FEATURES PHRASELIST '%s' versionId: '%s' on appId '%s'. Response: '%s'", phraseListId, versionId, appId, json.encode(response))
		return false, response
	end

	LogInfo("[LUIS_FEATURES:DeletePhraselist] Success deleted FEATURES PHRASELIST '%s' versionId: '%s' on appId '%s'.", phraseListId, versionId, appId)

	return true, response
end