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

function googleplay.module_type ()
	return "googleplay"
end

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

---
-- returns the conversation contact or member display text
--
function googleplay.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 googleplay.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 googleplay.getUserName(interaction, index, withType)
end

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

	if not interaction.events or not interaction.events[1] then
		--LogInfo("googleplay.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 googleplay.isPrivateMessage (interaction)
	return interaction.interactionData.subtype == "InboxNewMessage"
end

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

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

	interaction.properties = interaction.properties or {}

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

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

---
-- Takes an interaction and returns a block of text to be sent to the search engine
--
function googleplay.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 googleplay.calculateConversationTotalCharacters (interaction)
	assert(interaction)
	local messages = interaction.events or {}
	return common.calculateConversationTotalCharactersCommonChats(messages, interaction)
end

function googleplay.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

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

return googleplay