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

function whatsapp.module_type ()
	return "whatsapp"
end

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

function whatsapp.getExtendedInfo (interaction)

	if not interaction.events or not interaction.events[1] then
		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 the conversation contact or member display text
--
function whatsapp.getUserName (interaction, index)
	assert(type(index) == "number")

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

	local event = interaction.events[index]
	local agent_id = event.agent
	if not agent_id then
		--contact name
		if event.from and event.from.name and event.from.name ~= "" then
			return "text:"..event.from.name
		--address
		elseif event.address and event.address.Number and event.address.Number ~= "" then
			return "phone:"..event.address.Number
		--hidden address
		else
			return ""
		end
	else
		return "agent_id:"..agent_id
	end
end

---
-- Returns the first user name from the events array
--
function whatsapp.getDisplayName (interaction)
	return interaction.interactionData and interaction.interactionData.contactName or ""
end

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

	interaction.properties = interaction.properties or {}

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

	interaction.properties.display_name = whatsapp.getDisplayName(interaction)
	interaction.properties.has_attachments = whatsapp.hasAttachments(interaction)
	interaction.properties.summary = whatsapp.getExtendedInfo(interaction)
	interaction.properties.event_count = whatsapp.getEventsCountWithoutAutoResponse(interaction)
	interaction.properties.unread_event_count = whatsapp.getUnreadEventCount(interaction)
	interaction.properties.unanswered_event_count = whatsapp.getUnAnsweredContactEventCount(interaction)

	return interaction
end

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

function whatsapp.hasAttachments (interaction)
	assert(interaction)
	local messages = interaction.events
	if messages then
		for _, event in ipairs(messages) do
			local msgtype = (event.msgtype or (event.message and event.message.msgtype) or ""):lower()
			if msgtype == "attachment" then
				return true
			end
		end
	end
	return false
end

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

return whatsapp