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

function instagram.module_type ()
	return "instagram"
end

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

---
-- returns the conversation contact or member display text
--
function instagram.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.from.name or event.message.from.username or ""
	end
	local agent_id = event.agent
	if not agent_id then
		return "text:".. (event.message.from.name or event.message.from.username or "")
	else
		return "agent_id:"..agent_id
	end
end

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

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

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

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

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

	interaction.properties = interaction.properties or {}

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

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

---
-- Takes an interaction and returns a block of text to be sent to the search engine
--
function instagram.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

--[[
	Remuevo los Enter y retorno de carro.
]]--
local function SanitizeMessage (text)
	return m_helpers.string:CleanCR(text or "")
end

--[[
	
--]]
function instagram.calculateConversationTotalCharacters (interaction)
	assert(interaction)
	return common.calculateConversationTotalCharactersFacebookInstagram(interaction)
end

function instagram.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
-----------------------------------------------------------------
instagram.isTransferred                        = common.isTransferred
instagram.isTaken                              = common.isTaken
instagram.isWrappedUp                          = common.isWrappedUp
instagram.isFinished                           = common.isFinished
instagram.getConversationOwner                 = common.getConversationOwner
instagram.getFirstAssignedAgent                = common.getFirstAssignedAgent
instagram.getLastAgentEndsConversation         = common.getLastAgentEndsConversation
instagram.getLastEventTimestamp                = common.getLastEventTimestamp
instagram.updateReaders                        = common.updateReaders
instagram.updateLabels                         = common.updateLabels
instagram.getLastStep                          = common.getLastStep
instagram.isAutoResponseEvent                  = common.isAutoResponseEvent
instagram.getUnreadEventCount                  = common.getUnreadEventCount
instagram.getUnAnsweredContactEventCount	   = common.getUnAnsweredContactEventCount
instagram.getEventsCountWithoutAutoResponse    = common.getEventsCountWithoutAutoResponse
instagram.getAllEventsCount                    = common.getAllEventsCount
instagram.newInteractionEvent                  = common.newInteractionEvent
instagram.newInteractionEvents                 = common.newInteractionEvents
instagram.getSocialNetworkPostId               = common.getSocialNetworkPostId
instagram.getBatchId                           = common.getBatchId
instagram.getFirstTransferringInfo             = common.getFirstTransferringInfo
instagram.loadFirstPendingStep                 = common.loadFirstPendingStep
instagram.loadStatusInteraction                = common.loadStatusInteraction
instagram.loadFirstTakenStep                   = common.loadFirstTakenStep
instagram.loadStartAttention                   = common.loadStartAttention
instagram.loadTicket                           = common.loadTicket
instagram.loadFirstAgentResponse               = common.loadFirstAgentResponse
instagram.loadLastAgentResponse                = common.loadLastAgentResponse
instagram.loadSubType                          = common.loadSubType
instagram.loadPage                             = common.loadPage
instagram.getConversationTotals                = common.getConversationTotals
instagram.calculateConversationTimeSec         = instagram.calculateConversationTimeSec or common.calculateConversationTimeSec
instagram.calculateConversationTotalCharacters = instagram.calculateConversationTotalCharacters or common.calculateConversationTotalCharacters

return instagram