local c={}c.__index=c function c.SendSystemMessage(V,c,m)local R=V:InternalCreateMessageObject(c,nil,true,m)local O,L=pcall(function()V.eMessagePosted:Fire(R)end)if not O and L then print("\069\114\114\111\114 \112\111\115\116\105\110\103 \109\101\115\115\097\103\101\058 "..L)end V:InternalAddMessageToHistoryLog(R)for c,m in pairs(V.Speakers)do m:InternalSendSystemMessage(R,V.Name)end return R end function c.SendSystemMessageToSpeaker(R,c,m,V)local O=R.Speakers[m]if O then local m=R:InternalCreateMessageObject(c,nil,true,V)O:InternalSendSystemMessage(m,R.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",m,R.Name))end end function c.SendMessageObjToFilters(R,c,m,V)local O=m.Message m.Message=c R:InternalDoMessageFilter(V.Name,m,R.Name)R.ChatService:InternalDoMessageFilter(V.Name,m,R.Name)local L=m.Message m.Message=O return L end function c.CanCommunicateByUserId(V,c,m)if RunService:IsStudio()then return true end if c==0 or m==0 then return true end local R,O=pcall(function()return Chat:CanUsersChatAsync(c,m)end)return R and O end function c.CanCommunicate(V,c,m)local R=c:GetPlayer()local O=m:GetPlayer()if R and O then return V:CanCommunicateByUserId(R.UserId,O.UserId)end return true end function c.SendMessageToSpeaker(O,c,m,V,R)local L=O.Speakers[m]local Z=O.ChatService:GetSpeaker(V)if L and Z then local D=L:IsSpeakerMuted(V)if D then return end if not O:CanCommunicate(L,Z)then return end local f=m==V local d=O:InternalCreateMessageObject(c,V,f,R)c=O:SendMessageObjToFilters(c,d,V)L:InternalSendMessage(d,O.Name)if not IN_GAME_CHAT_USE_NEW_FILTER_API then local V=O.ChatService:InternalApplyRobloxFilter(d.FromSpeaker,c,m)if V then d.Message=V d.IsFiltered=true L:InternalSendFilteredMessage(d,O.Name)end else local m=O.Private and Enum.TextFilterContext.PrivateChat or Enum.TextFilterContext.PublicChat local V,R,Z=O.ChatService:InternalApplyRobloxFilterNewAPI(d.FromSpeaker,c,m)if V then d.FilterResult=Z d.IsFilterResult=R d.IsFiltered=true L:InternalSendFilteredMessageWithFilterResult(d,O.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",m,O.Name))end end function c.KickSpeaker(V,c,m)local R=V.ChatService:GetSpeaker(c)if not R then error("\083\112\101\097\107\101\114 \""..(c.."\" \100\111\101\115 \110\111\116 \101\120\105\115\116\033"))end local O=""local L=""if m then O=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",V.Name,m)L=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",c,m)else O=string.format("\089\111\117 \119\101\114\101 \107\105\099\107\101\100 \102\114\111\109 \'\037\115\'",V.Name)L=string.format("\037\115 \119\097\115 \107\105\099\107\101\100",c)end V:SendSystemMessageToSpeaker(O,c)R:LeaveChannel(V.Name)V:SendSystemMessage(L)end function c.MuteSpeaker(R,c,m,V)local O=R.ChatService:GetSpeaker(c)if not O then error("\083\112\101\097\107\101\114 \""..(c.."\" \100\111\101\115 \110\111\116 \101\120\105\115\116\033"))end R.Mutes[c:lower()]=(V==0 or V==nil)and 0 or os.time()+V if m then R: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",c,m))end local L,Z=pcall(function()R.eSpeakerMuted:Fire(c,m,V)end)if not L and Z then print("\069\114\114\111\114 \109\117\116\116\105\110\103 \115\112\101\097\107\101\114\058 "..Z)end local D=R.ChatService:GetSpeaker(c)if D then local c,O=pcall(function()D.eMuted:Fire(R.Name,m,V)end)if not c and O then print("\069\114\114\111\114 \109\117\116\116\105\110\103 \115\112\101\097\107\101\114\058 "..O)end end end function c.UnmuteSpeaker(m,c)local V=m.ChatService:GetSpeaker(c)if not V then error("\083\112\101\097\107\101\114 \""..(c.."\" \100\111\101\115 \110\111\116 \101\120\105\115\116\033"))end m.Mutes[c:lower()]=nil local R,O=pcall(function()m.eSpeakerUnmuted:Fire(c)end)if not R and O then print("\069\114\114\111\114 \117\110\109\117\116\105\110\103 \115\112\101\097\107\101\114\058 "..O)end local L=m.ChatService:GetSpeaker(c)if L then local c,V=pcall(function()L.eUnmuted:Fire(m.Name)end)if not c and V then print("\069\114\114\111\114 \117\110\109\117\116\105\110\103 \115\112\101\097\107\101\114\058 "..V)end end end function c.IsSpeakerMuted(m,c)return m.Mutes[c:lower()]~=nil end function c.GetSpeakerList(c)local m={}for c,V in pairs(c.Speakers)do table.insert(m,V.Name)end return m end function c.RegisterFilterMessageFunction(R,c,m,V)if R.FilterMessageFunctions:HasFunction(c)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",c))end R.FilterMessageFunctions:AddFunction(c,m,V)end function c.FilterMessageFunctionExists(m,c)return m.FilterMessageFunctions:HasFunction(c)end function c.UnregisterFilterMessageFunction(m,c)if not m.FilterMessageFunctions:HasFunction(c)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",c))end m.FilterMessageFunctions:RemoveFunction(c)end function c.RegisterProcessCommandsFunction(R,c,m,V)if R.ProcessCommandsFunctions:HasFunction(c)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",c))end R.ProcessCommandsFunctions:AddFunction(c,m,V)end function c.ProcessCommandsFunctionExists(m,c)return m.ProcessCommandsFunctions:HasFunction(c)end function c.UnregisterProcessCommandsFunction(m,c)if not m.ProcessCommandsFunctions:HasFunction(c)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",c))end m.ProcessCommandsFunctions:RemoveFunction(c)end local function m(c)local m={}for c,V in pairs(c)do m[c]=V end return m end function c.GetHistoryLog(c)return m(c.ChatHistory)end function c.GetHistoryLogForSpeaker(V,c)local R=-1 local O=c:GetPlayer()if O then R=O.UserId end local L={}if not IN_GAME_CHAT_USE_NEW_FILTER_API then for c=1,#V.ChatHistory,1 do local O=V.ChatHistory[c].SpeakerUserId if V:CanCommunicateByUserId(R,O)then table.insert(L,m(V.ChatHistory[c]))end end else for c=1,#V.ChatHistory,1 do local Z=V.ChatHistory[c].SpeakerUserId if V:CanCommunicateByUserId(R,Z)then local R=m(V.ChatHistory[c])if R.MessageType==ChatConstants.MessageTypeDefault or R.MessageType==ChatConstants.MessageTypeMeCommand then local c=R.FilterResult if R.IsFilterResult then if O then R.Message=c:GetChatForUserAsync(O.UserId)else R.Message=c:GetNonChatStringForBroadcastAsync()end else R.Message=c end end table.insert(L,R)end end end return L 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 textContext = self.Private and Enum.TextFilterContext.PrivateChat or Enum.TextFilterContext.PublicChat
			local filterSuccess, isFilterResult, filteredMessage = self.ChatService:InternalApplyRobloxFilterNewAPI(
				messageObj.FromSpeaker,
				message,
				textContext
			)
			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
