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

function youtube.module_type ()
	return "youtube"
end

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

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

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

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

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

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

	interaction.properties = interaction.properties or {}

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

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

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

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

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

return youtube