local m_helpers = require "helpers"
local common = require "interactionmanip.common"
local twitter = {}


function twitter.module_type ()
	return "twitter"
end

function twitter.getMessage (interaction, index)
	assert(type(index) == "number")

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

	local event = interaction.events[index]
	return event.text
end

local getSocialNetworkPostId_subtypes = {
	TWEET_REPLY = function(interaction)
		if not interaction.events or #interaction.events < 1 then
			return nil
		end
		return interaction.events[1].id_str
	end,
	QUOTED = function(interaction)
		if not interaction.events or #interaction.events < 1 then
			return nil
		end
		return interaction.events[1].quoted_status_id_str
	end
}

function twitter.getSocialNetworkPostId (interaction)
	local postId = common.getSocialNetworkPostId (interaction)
	if postId then
		return postId
	end
	local subtype = interaction.interactionData and interaction.interactionData.subtype or ""
	local getFunction = getSocialNetworkPostId_subtypes[subtype]
	return getFunction and getFunction(interaction) or nil
end

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

	interaction.properties = interaction.properties or {}

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

	interaction.properties.first_message_text = twitter.getMessage(interaction, 1)
	interaction.properties.event_count = twitter.getEventsCountWithoutAutoResponse(interaction)
	interaction.properties.has_attachments = twitter.hasAttachments(interaction)
	interaction.properties.unread_event_count = twitter.getUnreadEventCount(interaction)
	interaction.properties.unanswered_event_count = twitter.getUnAnsweredContactEventCount(interaction)
	interaction.interactionData.postId = interaction.interactionData.postId or twitter.getSocialNetworkPostId(interaction)

	return interaction
end

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

	for i=1, #interaction.events do
		table.insert(data, twitter.getMessage(interaction, i))
	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 twitter.calculateConversationTotalCharacters (interaction)
	assert(interaction)
	local function MustCalculate(message)
		local text = message.text
		if type(text) ~= "string" then
			LogDebug("[INTERACTIONMAINIP.twitter.calculateConversationTotalCharactersCommonChats] Only calculate 'text' messages. Current text: '%s'", tostring(text))
			return false
		end
		return true, text
	end
	local function SanitizeMessage (text)
		return m_helpers.string:CleanCR(text or "")
	end
	local messages = interaction.events
	return common.calculateConversationTotalCharactersCommonChats(messages, interaction, MustCalculate, SanitizeMessage)
end

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

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

return twitter
