local common = require "interactionmanip.common"
local cjson = require "cjson"
local utf8 = require "icu.utf8"
local appstore = {}

function appstore.module_type ()
	return "appstore"
end

local function getMessageText(message)
	return message.text or ""
end

---
-- returns the conversation contact or member display text
--
function appstore.getUserName (interaction, index, withType)
	assert(type(index) == "number")

	if not interaction.events or not interaction.events[index] then
		return ""
	end

	local event = interaction.events[index]
	if not withType then
		return event.message.name
	end
	local agent_id = event.agent
	if not agent_id then
		return "text:"..event.message.name
	else
		return "agent_id:"..agent_id
	end
end

---
-- Returns the first user name from the events array
--
function appstore.getDisplayName (interaction, withType)
	local index = 1
	if interaction.interactionData and 
		(interaction.interactionData.subtype == "NewPostComment" or interaction.interactionData.subtype == "NewLivePostMessage")
		and interaction.events and #interaction.events > 1 
	then
		index = 2
	end
	return appstore.getUserName(interaction, index, withType)
end

function appstore.getExtendedInfo (interaction)
	--LogInfo("appstore.getExtendedInfo id: '%s'", interaction.id)

	if not interaction.events or not interaction.events[1] then
		--LogInfo("appstore.getExtendedInfo nos fuimos")
		return ""
	end

	local event = interaction.events[1]

	local message = getMessageText(event.message)
	if type(message) == "string" then
		return utf8.sub(message, 1, 200)
	end

	return ""
end

---
-- returns true if at least one event is a private message
function appstore.isPrivateMessage (interaction)
	return interaction.interactionData.subtype == "InboxNewMessage"
end

---
-- Takes an interaction and precomputes properties based on events
--
function appstore.updateInteraction (interaction)

	--LogWarning("Updating interaction '%s'", interaction.id)

	interaction.properties = interaction.properties or {}

	appstore.updateReaders(interaction)
	appstore.updateLabels(interaction)
	appstore.isTransferred(interaction)
	appstore.getLastAgentEndsConversation(interaction)
	appstore.getLastStep(interaction)

	interaction.properties.display_name = appstore.getDisplayName(interaction, true)
	interaction.properties.summary = appstore.getExtendedInfo(interaction)
	interaction.properties.event_count = appstore.getEventsCountWithoutAutoResponse(interaction)
	interaction.properties.unread_event_count = appstore.getUnreadEventCount(interaction)
	interaction.properties.is_private_message = appstore.isPrivateMessage(interaction)
	interaction.properties.has_attachments = appstore.hasAttachments(interaction)
	return interaction
end

---
-- Takes an interaction and returns a block of text to be sent to the search engine
--
function appstore.getSearchableContent (interaction)
	if not interaction.events then return "" end
	local data = {}

	for _, event in ipairs(interaction.events) do
		table.insert(data, getMessageText(event.message))
	end

	if interaction.comments then
		for _, comment in pairs(interaction.comments) do
			table.insert(data, comment.comment)
			table.insert(data, comment.authorName)
		end
	end

	return table.concat(data, " ")
end

function appstore.calculateConversationTotalCharacters (interaction)
	assert(interaction)
	local messages = interaction.events or {}
	return common.calculateConversationTotalCharactersCommonChats(messages, interaction)
end

function appstore.hasAttachments (interaction)
	assert(interaction)
	local messages = interaction.events
	if messages then
		for _, event in ipairs(messages) do
			if event.message and event.message.attachments and #event.message.attachments > 0 then
				return true
			end
		end
	end
	return false
end

------------------------------------------------
appstore.isTransferred                        = common.isTransferred
appstore.isTaken                              = common.isTaken
appstore.isWrappedUp                          = common.isWrappedUp
appstore.isFinished                           = common.isFinished
appstore.getConversationOwner                 = common.getConversationOwner
appstore.getFirstAssignedAgent                = common.getFirstAssignedAgent
appstore.getLastAgentEndsConversation         = common.getLastAgentEndsConversation
appstore.getLastEventTimestamp                = common.getLastEventTimestamp
appstore.updateReaders                        = common.updateReaders
appstore.updateLabels                         = common.updateLabels
appstore.getLastStep                          = common.getLastStep
appstore.isAutoResponseEvent                  = common.isAutoResponseEvent
appstore.getUnreadEventCount                  = common.getUnreadEventCount
appstore.getEventsCountWithoutAutoResponse    = common.getEventsCountWithoutAutoResponse
appstore.getAllEventsCount                    = common.getAllEventsCount
appstore.newInteractionEvent                  = common.newInteractionEvent
appstore.newInteractionEvents                 = common.newInteractionEvents
appstore.getSocialNetworkPostId               = common.getSocialNetworkPostId
appstore.getBatchId                           = common.getBatchId
appstore.getFirstTransferringInfo             = common.getFirstTransferringInfo
appstore.loadFirstPendingStep                 = common.loadFirstPendingStep
appstore.loadStatusInteraction                = common.loadStatusInteraction
appstore.loadFirstTakenStep                   = common.loadFirstTakenStep
appstore.loadStartAttention                   = common.loadStartAttention
appstore.loadTicket                           = common.loadTicket
appstore.loadFirstAgentResponse               = common.loadFirstAgentResponse
appstore.loadLastAgentResponse                = common.loadLastAgentResponse
appstore.loadSubType                          = common.loadSubType
appstore.getConversationTotals                = common.getConversationTotals
appstore.calculateConversationTimeSec         = appstore.calculateConversationTimeSec or common.calculateConversationTimeSec
appstore.calculateConversationTotalCharacters = appstore.calculateConversationTotalCharacters or common.calculateConversationTotalCharacters

return appstore