local X={}X.__index=X function X.SendSystemMessage(E,X,G)local m=E:InternalCreateMessageObject(X,nil,true,G)local C,a=pcall(function()E.eMessagePosted:Fire(m)end)if not C and a then print("\069\114\114\111\114 \112\111\115\116\105\110\103 \109\101\115\115\097\103\101\058 "..a)end E:InternalAddMessageToHistoryLog(m)for X,G in pairs(E.Speakers)do G:InternalSendSystemMessage(m,E.Name)end return m end function X.SendSystemMessageToSpeaker(m,X,G,E)local C=m.Speakers[G]if C then local G=m:InternalCreateMessageObject(X,nil,true,E)C:InternalSendSystemMessage(G,m.Name)else warn(string.format("\083\112\101\097\107\101\114 \'\037\115\' \105\115 \110\111\116 \105\110 \099\104\097\110\110\101\108 \'\037\115\' \097\110\100 \099\097\110\110\111\116 \098\101 \115\101\110\116 \097 \115\121\115\116\101\109 \109\101\115\115\097\103\101",G,m.Name))end end function X.SendMessageObjToFilters(m,X,G,E)local C=G.Message G.Message=X m:InternalDoMessageFilter(E.Name,G,m.Name)m.ChatService:InternalDoMessageFilter(E.Name,G,m.Name)local a=G.Message G.Message=C return a end function X.CanCommunicateByUserId(E,X,G)if RunService:IsStudio()then return true end if X==0 or G==0 then return true end local m,C=pcall(function()return Chat:CanUsersChatAsync(X,G)end)return m and C end function X.CanCommunicate(E,X,G)local m=X:GetPlayer()local C=G:GetPlayer()if m and C then return E:CanCommunicateByUserId(m.UserId,C.UserId)end return true end function X.SendMessageToSpeaker(C,X,G,E,m)local a=C.Speakers[G]local h=C.ChatService:GetSpeaker(E)if a and h then local B=a:IsSpeakerMuted(E)if B then return end if not C:CanCommunicate(a,h)then return end local l=G==E local K=C:InternalCreateMessageObject(X,E,l,m)X=C:SendMessageObjToFilters(X,K,E)a:InternalSendMessage(K,C.Name)if not IN_GAME_CHAT_USE_NEW_FILTER_API then local E=C.ChatService:InternalApplyRobloxFilter(K.FromSpeaker,X,G)if E then K.Message=E K.IsFiltered=true a:InternalSendFilteredMessage(K,C.Name)end else local G,E,m=C.ChatService:InternalApplyRobloxFilterNewAPI(K.FromSpeaker,X)if G then K.FilterResult=m K.IsFilterResult=E K.IsFiltered=true a:InternalSendFilteredMessageWithFilterResult(K,C.Name)end end else warn(string.format("\083\112\101\097\107\101\114 \'\037\115\' \105\115 \110\111\116 \105\110 \099\104\097\110\110\101\108 \'\037\115\' \097\110\100 \099\097\110\110\111\116 \098\101 \115\101\110\116 \097 \109\101\115\115\097\103\101",G,C.Name))end end function X.KickSpeaker(E,X,G)local m=E.ChatService:GetSpeaker(X)if not m then error("\083\112\101\097\107\101\114 \""..(X.."\" \100\111\101\115 \110\111\116 \101\120\105\115\116\033"))end local C=""local a=""if G then C=string.format("\089\111\117 \119\101\114\101 \107\105\099\107\101\100 \102\114\111\109 \'\037\115\' \102\111\114 \116\104\101 \102\111\108\108\111\119\105\110\103 \114\101\097\115\111\110\040\115\041\058 \037\115",E.Name,G)a=string.format("\037\115 \119\097\115 \107\105\099\107\101\100 \102\111\114 \116\104\101 \102\111\108\108\111\119\105\110\103 \114\101\097\115\111\110\040\115\041\058 \037\115",X,G)else C=string.format("\089\111\117 \119\101\114\101 \107\105\099\107\101\100 \102\114\111\109 \'\037\115\'",E.Name)a=string.format("\037\115 \119\097\115 \107\105\099\107\101\100",X)end E:SendSystemMessageToSpeaker(C,X)m:LeaveChannel(E.Name)E:SendSystemMessage(a)end function X.MuteSpeaker(m,X,G,E)local C=m.ChatService:GetSpeaker(X)if not C then error("\083\112\101\097\107\101\114 \""..(X.."\" \100\111\101\115 \110\111\116 \101\120\105\115\116\033"))end m.Mutes[X:lower()]=(E==0 or E==nil)and 0 or os.time()+E if G then m:SendSystemMessage(string.format("\037\115 \119\097\115 \109\117\116\101\100 \102\111\114 \116\104\101 \102\111\108\108\111\119\105\110\103 \114\101\097\115\111\110\040\115\041\058 \037\115",X,G))end local a,h=pcall(function()m.eSpeakerMuted:Fire(X,G,E)end)if not a and h then print("\069\114\114\111\114 \109\117\116\116\105\110\103 \115\112\101\097\107\101\114\058 "..h)end local B=m.ChatService:GetSpeaker(X)if B then local X,C=pcall(function()B.eMuted:Fire(m.Name,G,E)end)if not X and C then print("\069\114\114\111\114 \109\117\116\116\105\110\103 \115\112\101\097\107\101\114\058 "..C)end end end function X.UnmuteSpeaker(G,X)local E=G.ChatService:GetSpeaker(X)if not E then error("\083\112\101\097\107\101\114 \""..(X.."\" \100\111\101\115 \110\111\116 \101\120\105\115\116\033"))end G.Mutes[X:lower()]=nil local m,C=pcall(function()G.eSpeakerUnmuted:Fire(X)end)if not m and C then print("\069\114\114\111\114 \117\110\109\117\116\105\110\103 \115\112\101\097\107\101\114\058 "..C)end local a=G.ChatService:GetSpeaker(X)if a then local X,E=pcall(function()a.eUnmuted:Fire(G.Name)end)if not X and E then print("\069\114\114\111\114 \117\110\109\117\116\105\110\103 \115\112\101\097\107\101\114\058 "..E)end end end function X.IsSpeakerMuted(G,X)return G.Mutes[X:lower()]~=nil end function X.GetSpeakerList(X)local G={}for X,E in pairs(X.Speakers)do table.insert(G,E.Name)end return G end function X.RegisterFilterMessageFunction(m,X,G,E)if m.FilterMessageFunctions:HasFunction(X)then error(string.format("\070\105\108\116\101\114\077\101\115\115\097\103\101\070\117\110\099\116\105\111\110 \'\037\115\' \097\108\114\101\097\100\121 \101\120\105\115\116\115",X))end m.FilterMessageFunctions:AddFunction(X,G,E)end function X.FilterMessageFunctionExists(G,X)return G.FilterMessageFunctions:HasFunction(X)end function X.UnregisterFilterMessageFunction(G,X)if not G.FilterMessageFunctions:HasFunction(X)then error(string.format("\070\105\108\116\101\114\077\101\115\115\097\103\101\070\117\110\099\116\105\111\110 \'\037\115\' \100\111\101\115 \110\111\116 \101\120\105\115\116\115",X))end G.FilterMessageFunctions:RemoveFunction(X)end function X.RegisterProcessCommandsFunction(m,X,G,E)if m.ProcessCommandsFunctions:HasFunction(X)then error(string.format("\080\114\111\099\101\115\115\067\111\109\109\097\110\100\115\070\117\110\099\116\105\111\110 \'\037\115\' \097\108\114\101\097\100\121 \101\120\105\115\116\115",X))end m.ProcessCommandsFunctions:AddFunction(X,G,E)end function X.ProcessCommandsFunctionExists(G,X)return G.ProcessCommandsFunctions:HasFunction(X)end function X.UnregisterProcessCommandsFunction(G,X)if not G.ProcessCommandsFunctions:HasFunction(X)then error(string.format("\080\114\111\099\101\115\115\067\111\109\109\097\110\100\115\070\117\110\099\116\105\111\110 \'\037\115\' \100\111\101\115 \110\111\116 \101\120\105\115\116",X))end G.ProcessCommandsFunctions:RemoveFunction(X)end local function G(X)local G={}for X,E in pairs(X)do G[X]=E end return G end function X.GetHistoryLog(X)return G(X.ChatHistory)end function X.GetHistoryLogForSpeaker(E,X)local m=-1 local C=X:GetPlayer()if C then m=C.UserId end local a={}if not IN_GAME_CHAT_USE_NEW_FILTER_API then for X=1,#E.ChatHistory,1 do local C=E.ChatHistory[X].SpeakerUserId if E:CanCommunicateByUserId(m,C)then table.insert(a,G(E.ChatHistory[X]))end end else for X=1,#E.ChatHistory,1 do local h=E.ChatHistory[X].SpeakerUserId if E:CanCommunicateByUserId(m,h)then local m=G(E.ChatHistory[X])if m.MessageType==ChatConstants.MessageTypeDefault or m.MessageType==ChatConstants.MessageTypeMeCommand then local X=m.FilterResult if m.IsFilterResult then if C then m.Message=X:GetChatForUserAsync(C.UserId)else m.Message=X:GetNonChatStringForBroadcastAsync()end else m.Message=X end end table.insert(a,m)end end end return a end


local methods = {}
methods.__index = methods

function methods:SendSystemMessage(message, extraData)
	local messageObj = self:InternalCreateMessageObject(message, nil, true, extraData)

	local success, err = pcall(function() self.eMessagePosted:Fire(messageObj) end)
	if not success and err then
		print("Error posting message: " ..err)
	end

	self:InternalAddMessageToHistoryLog(messageObj)

	for i, speaker in pairs(self.Speakers) do
		speaker:InternalSendSystemMessage(messageObj, self.Name)
	end

	return messageObj
end

function methods:SendSystemMessageToSpeaker(message, speakerName, extraData)
	local speaker = self.Speakers[speakerName]
	if (speaker) then
		local messageObj = self:InternalCreateMessageObject(message, nil, true, extraData)
		speaker:InternalSendSystemMessage(messageObj, self.Name)
	else
		warn(string.format("Speaker '%s' is not in channel '%s' and cannot be sent a system message", speakerName, self.Name))
	end
end

function methods:SendMessageObjToFilters(message, messageObj, fromSpeaker)
	local oldMessage = messageObj.Message
	messageObj.Message = message
	self:InternalDoMessageFilter(fromSpeaker.Name, messageObj, self.Name)
	self.ChatService:InternalDoMessageFilter(fromSpeaker.Name, messageObj, self.Name)
	local newMessage = messageObj.Message
	messageObj.Message = oldMessage
	return newMessage
end

function methods:CanCommunicateByUserId(userId1, userId2)
	if RunService:IsStudio() then
		return true
	end
	-- UserId is set as 0 for non player speakers.
	if userId1 == 0 or userId2 == 0 then
		return true
	end
	local success, canCommunicate = pcall(function()
		return Chat:CanUsersChatAsync(userId1, userId2)
	end)
	return success and canCommunicate
end

function methods:CanCommunicate(speakerObj1, speakerObj2)
	local player1 = speakerObj1:GetPlayer()
	local player2 = speakerObj2:GetPlayer()
	if player1 and player2 then
		return self:CanCommunicateByUserId(player1.UserId, player2.UserId)
	end
	return true
end

function methods:SendMessageToSpeaker(message, speakerName, fromSpeakerName, extraData)
	local speakerTo = self.Speakers[speakerName]
	local speakerFrom = self.ChatService:GetSpeaker(fromSpeakerName)
	if speakerTo and speakerFrom then
		local isMuted = speakerTo:IsSpeakerMuted(fromSpeakerName)
		if isMuted then
			return
		end

		if not self:CanCommunicate(speakerTo, speakerFrom) then
			return
		end

		-- We need to claim the message is filtered even if it not in this case for compatibility with legacy client side code.
		local isFiltered = speakerName == fromSpeakerName
		local messageObj = self:InternalCreateMessageObject(message, fromSpeakerName, isFiltered, extraData)
		message = self:SendMessageObjToFilters(message, messageObj, fromSpeakerName)
		speakerTo:InternalSendMessage(messageObj, self.Name)

		--// START FFLAG
		if (not IN_GAME_CHAT_USE_NEW_FILTER_API) then --// USES FFLAG
		--// OLD BEHAVIOR
		local filteredMessage = self.ChatService:InternalApplyRobloxFilter(messageObj.FromSpeaker, message, speakerName)
		if filteredMessage then
			messageObj.Message = filteredMessage
			messageObj.IsFiltered = true
			speakerTo:InternalSendFilteredMessage(messageObj, self.Name)
		end
		--// OLD BEHAVIOR
		else
		--// NEW BEHAVIOR
			local filterSuccess, isFilterResult, filteredMessage = self.ChatService:InternalApplyRobloxFilterNewAPI(messageObj.FromSpeaker, message)
			if (filterSuccess) then
				messageObj.FilterResult = filteredMessage
				messageObj.IsFilterResult = isFilterResult
				messageObj.IsFiltered = true
				speakerTo:InternalSendFilteredMessageWithFilterResult(messageObj, self.Name)
			end
		--// NEW BEHAVIOR
		end
		--// END FFLAG
	else
		warn(string.format("Speaker '%s' is not in channel '%s' and cannot be sent a message", speakerName, self.Name))
	end
end

function methods:KickSpeaker(speakerName, reason)
	local speaker = self.ChatService:GetSpeaker(speakerName)
	if (not speaker) then
		error("Speaker \"" .. speakerName .. "\" does not exist!")
	end

	local messageToSpeaker = ""
	local messageToChannel = ""

	if (reason) then
		messageToSpeaker = string.format("You were kicked from '%s' for the following reason(s): %s", self.Name, reason)
		messageToChannel = string.format("%s was kicked for the following reason(s): %s", speakerName, reason)
	else
		messageToSpeaker = string.format("You were kicked from '%s'", self.Name)
		messageToChannel = string.format("%s was kicked", speakerName)
	end

	self:SendSystemMessageToSpeaker(messageToSpeaker, speakerName)
	speaker:LeaveChannel(self.Name)
	self:SendSystemMessage(messageToChannel)
end

function methods:MuteSpeaker(speakerName, reason, length)
	local speaker = self.ChatService:GetSpeaker(speakerName)
	if (not speaker) then
		error("Speaker \"" .. speakerName .. "\" does not exist!")
	end

	self.Mutes[speakerName:lower()] = (length == 0 or length == nil) and 0 or (os.time() + length)

	if (reason) then
		self:SendSystemMessage(string.format("%s was muted for the following reason(s): %s", speakerName, reason))
	end

	local success, err = pcall(function() self.eSpeakerMuted:Fire(speakerName, reason, length) end)
	if not success and err then
		print("Error mutting speaker: " ..err)
	end

	local spkr = self.ChatService:GetSpeaker(speakerName)
	if (spkr) then
		local success, err = pcall(function() spkr.eMuted:Fire(self.Name, reason, length) end)
		if not success and err then
			print("Error mutting speaker: " ..err)
		end
	end

end

function methods:UnmuteSpeaker(speakerName)
	local speaker = self.ChatService:GetSpeaker(speakerName)
	if (not speaker) then
		error("Speaker \"" .. speakerName .. "\" does not exist!")
	end

	self.Mutes[speakerName:lower()] = nil

	local success, err = pcall(function() self.eSpeakerUnmuted:Fire(speakerName) end)
	if not success and err then
		print("Error unmuting speaker: " ..err)
	end

	local spkr = self.ChatService:GetSpeaker(speakerName)
	if (spkr) then
		local success, err = pcall(function() spkr.eUnmuted:Fire(self.Name) end)
		if not success and err then
			print("Error unmuting speaker: " ..err)
		end
	end
end

function methods:IsSpeakerMuted(speakerName)
	return (self.Mutes[speakerName:lower()] ~= nil)
end

function methods:GetSpeakerList()
	local list = {}
	for i, speaker in pairs(self.Speakers) do
		table.insert(list, speaker.Name)
	end
	return list
end

function methods:RegisterFilterMessageFunction(funcId, func, priority)
	if self.FilterMessageFunctions:HasFunction(funcId) then
		error(string.format("FilterMessageFunction '%s' already exists", funcId))
	end
	self.FilterMessageFunctions:AddFunction(funcId, func, priority)
end

function methods:FilterMessageFunctionExists(funcId)
	return self.FilterMessageFunctions:HasFunction(funcId)
end

function methods:UnregisterFilterMessageFunction(funcId)
	if not self.FilterMessageFunctions:HasFunction(funcId) then
		error(string.format("FilterMessageFunction '%s' does not exists", funcId))
	end
	self.FilterMessageFunctions:RemoveFunction(funcId)
end

function methods:RegisterProcessCommandsFunction(funcId, func, priority)
	if self.ProcessCommandsFunctions:HasFunction(funcId) then
		error(string.format("ProcessCommandsFunction '%s' already exists", funcId))
	end
	self.ProcessCommandsFunctions:AddFunction(funcId, func, priority)
end

function methods:ProcessCommandsFunctionExists(funcId)
	return self.ProcessCommandsFunctions:HasFunction(funcId)
end

function methods:UnregisterProcessCommandsFunction(funcId)
	if not self.ProcessCommandsFunctions:HasFunction(funcId) then
		error(string.format("ProcessCommandsFunction '%s' does not exist", funcId))
	end
	self.ProcessCommandsFunctions:RemoveFunction(funcId)
end

local function ShallowCopy(table)
	local copy = {}
	for i, v in pairs(table) do
		copy[i] = v
	end
	return copy
end

function methods:GetHistoryLog()
	return ShallowCopy(self.ChatHistory)
end

function methods:GetHistoryLogForSpeaker(speaker)
	local userId = -1
	local player = speaker:GetPlayer()
	if player then
		userId = player.UserId
	end
	local chatlog = {}
	--// START FFLAG
	if (not IN_GAME_CHAT_USE_NEW_FILTER_API) then --// USES FFLAG
	--// OLD BEHAVIOR
	for i = 1, #self.ChatHistory do
		local logUserId = self.ChatHistory[i].SpeakerUserId
		if self:CanCommunicateByUserId(userId, logUserId) then
			table.insert(chatlog, ShallowCopy(self.ChatHistory[i]))
		end
	end
	--// OLD BEHAVIOR
	else
	--// NEW BEHAVIOR
		for i = 1, #self.ChatHistory do
			local logUserId = self.ChatHistory[i].SpeakerUserId
			if self:CanCommunicateByUserId(userId, logUserId) then
				local messageObj = ShallowCopy(self.ChatHistory[i])

				--// Since we're using the new filter API, we need to convert the stored filter result
				--// into an actual string message to send to players for their chat history.
				--// System messages aren't filtered the same way, so they just have a regular 
				--// text value in the Message field.
				if (messageObj.MessageType == ChatConstants.MessageTypeDefault or messageObj.MessageType == ChatConstants.MessageTypeMeCommand) then
					local filterResult = messageObj.FilterResult
					if (messageObj.IsFilterResult) then
						if (player) then
							messageObj.Message = filterResult:GetChatForUserAsync(player.UserId)
						else
							messageObj.Message = filterResult:GetNonChatStringForBroadcastAsync()
						end
					else
						messageObj.Message = filterResult
					end
				end

				table.insert(chatlog, messageObj)
			end
		end
	--// NEW BEHAVIOR
	end
	--// END FFLAG
	return chatlog
end
