local z={}z.__index=z function z.SendSystemMessage(K,z,p)local M=K:InternalCreateMessageObject(z,nil,true,p)local b,h=pcall(function()K.eMessagePosted:Fire(M)end)if not b and h then print("\069\114\114\111\114 \112\111\115\116\105\110\103 \109\101\115\115\097\103\101\058 "..h)end K:InternalAddMessageToHistoryLog(M)for z,p in pairs(K.Speakers)do p:InternalSendSystemMessage(M,K.Name)end return M end function z.SendSystemMessageToSpeaker(M,z,p,K)local b=M.Speakers[p]if b then local p=M:InternalCreateMessageObject(z,nil,true,K)b:InternalSendSystemMessage(p,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",p,M.Name))end end function z.SendMessageObjToFilters(M,z,p,K)local b=p.Message p.Message=z M:InternalDoMessageFilter(K.Name,p,M.Name)M.ChatService:InternalDoMessageFilter(K.Name,p,M.Name)local h=p.Message p.Message=b return h end function z.CanCommunicateByUserId(K,z,p)if RunService:IsStudio()then return true end if z==0 or p==0 then return true end local M,b=pcall(function()return Chat:CanUsersChatAsync(z,p)end)return M and b end function z.CanCommunicate(K,z,p)local M=z:GetPlayer()local b=p:GetPlayer()if M and b then return K:CanCommunicateByUserId(M.UserId,b.UserId)end return true end function z.SendMessageToSpeaker(b,z,p,K,M)local h=b.Speakers[p]local N=b.ChatService:GetSpeaker(K)if h and N then local y=h:IsSpeakerMuted(K)if y then return end if not b:CanCommunicate(h,N)then return end local q=p==K local P=b:InternalCreateMessageObject(z,K,q,M)z=b:SendMessageObjToFilters(z,P,K)h:InternalSendMessage(P,b.Name)local o=b.ChatService:InternalApplyRobloxFilter(P.FromSpeaker,z,p)if o then P.Message=o P.IsFiltered=true h:InternalSendFilteredMessage(P,b.Name)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",p,b.Name))end end function z.KickSpeaker(K,z,p)local M=K.ChatService:GetSpeaker(z)if not M then error("\083\112\101\097\107\101\114 \""..(z.."\" \100\111\101\115 \110\111\116 \101\120\105\115\116\033"))end local b=""local h=""if p then b=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",K.Name,p)h=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",z,p)else b=string.format("\089\111\117 \119\101\114\101 \107\105\099\107\101\100 \102\114\111\109 \'\037\115\'",K.Name)h=string.format("\037\115 \119\097\115 \107\105\099\107\101\100",z)end K:SendSystemMessageToSpeaker(b,z)M:LeaveChannel(K.Name)K:SendSystemMessage(h)end function z.MuteSpeaker(M,z,p,K)local b=M.ChatService:GetSpeaker(z)if not b then error("\083\112\101\097\107\101\114 \""..(z.."\" \100\111\101\115 \110\111\116 \101\120\105\115\116\033"))end M.Mutes[z:lower()]=(K==0 or K==nil)and 0 or os.time()+K if p 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",z,p))end local h,N=pcall(function()M.eSpeakerMuted:Fire(z,p,K)end)if not h and N then print("\069\114\114\111\114 \109\117\116\116\105\110\103 \115\112\101\097\107\101\114\058 "..N)end local y=M.ChatService:GetSpeaker(z)if y then local z,b=pcall(function()y.eMuted:Fire(M.Name,p,K)end)if not z and b then print("\069\114\114\111\114 \109\117\116\116\105\110\103 \115\112\101\097\107\101\114\058 "..b)end end end function z.UnmuteSpeaker(p,z)local K=p.ChatService:GetSpeaker(z)if not K then error("\083\112\101\097\107\101\114 \""..(z.."\" \100\111\101\115 \110\111\116 \101\120\105\115\116\033"))end p.Mutes[z:lower()]=nil local M,b=pcall(function()p.eSpeakerUnmuted:Fire(z)end)if not M and b then print("\069\114\114\111\114 \117\110\109\117\116\105\110\103 \115\112\101\097\107\101\114\058 "..b)end local h=p.ChatService:GetSpeaker(z)if h then local z,K=pcall(function()h.eUnmuted:Fire(p.Name)end)if not z and K then print("\069\114\114\111\114 \117\110\109\117\116\105\110\103 \115\112\101\097\107\101\114\058 "..K)end end end function z.IsSpeakerMuted(p,z)return p.Mutes[z:lower()]~=nil end function z.GetSpeakerList(z)local p={}for z,K in pairs(z.Speakers)do table.insert(p,K.Name)end return p end function z.RegisterFilterMessageFunction(M,z,p,K)if M.FilterMessageFunctions:HasFunction(z)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",z))end M.FilterMessageFunctions:AddFunction(z,p,K)end function z.FilterMessageFunctionExists(p,z)return p.FilterMessageFunctions:HasFunction(z)end function z.UnregisterFilterMessageFunction(p,z)if not p.FilterMessageFunctions:HasFunction(z)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",z))end p.FilterMessageFunctions:RemoveFunction(z)end function z.RegisterProcessCommandsFunction(M,z,p,K)if M.ProcessCommandsFunctions:HasFunction(z)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",z))end M.ProcessCommandsFunctions:AddFunction(z,p,K)end function z.ProcessCommandsFunctionExists(p,z)return p.ProcessCommandsFunctions:HasFunction(z)end function z.UnregisterProcessCommandsFunction(p,z)if not p.ProcessCommandsFunctions:HasFunction(z)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",z))end p.ProcessCommandsFunctions:RemoveFunction(z)end local function p(z)local K={}for M,b in pairs(z)do if type(b)==z then K[M]=p(b)else K[M]=b end end return K end function z.GetHistoryLog(z)return p(z.ChatHistory)end function z.GetHistoryLogForSpeaker(K,z)local M=-1 local b=z:GetPlayer()if b then M=b.UserId end local h={}for z=1,#K.ChatHistory,1 do local b=K.ChatHistory[z].SpeakerUserId if K:CanCommunicateByUserId(M,b)then table.insert(h,p(K.ChatHistory[z]))end end return h 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)

		local filteredMessage = self.ChatService:InternalApplyRobloxFilter(messageObj.FromSpeaker, message, speakerName)
		if filteredMessage then
			messageObj.Message = filteredMessage
			messageObj.IsFiltered = true
			speakerTo:InternalSendFilteredMessage(messageObj, self.Name)
		end
	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 DeepCopy(table)
	local copy =	{}
	for i, v in pairs(table) do
		if (type(v) == table) then
			copy[i] = DeepCopy(v)
		else
			copy[i] = v
		end
	end
	return copy
end

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

function methods:GetHistoryLogForSpeaker(speaker)
	local userId = -1
	local player = speaker:GetPlayer()
	if player then
		userId = player.UserId
	end
	local chatlog = {}
	for i = 1, #self.ChatHistory do
		local logUserId = self.ChatHistory[i].SpeakerUserId
		if self:CanCommunicateByUserId(userId, logUserId) then
			table.insert(chatlog, DeepCopy(self.ChatHistory[i]))
		end
	end
	return chatlog
end
