-- Display a message to the client for a short time, with a background that covers the user's screen.



local tweenService = game:GetService('TweenService')
local playersService = game:GetService('Players')
local localPlayer = playersService.LocalPlayer
local gui = script:WaitForChild('MessageTakeoverGui')
local background = gui:WaitForChild('Background')
local textLabel = gui:WaitForChild('TextLabel')


local TRANSITION_TIME = .5
local DEFAULT_MESSAGE_DURATION = 4

local changeIndex = 0
local messageTakeoverModule = {}


messageTakeoverModule.ShowMessage = function(text, duration)
	if text then
		textLabel.Text = text
	end
	local playerGui = localPlayer:FindFirstChild('PlayerGui')
	if playerGui then
		changeIndex = changeIndex + 1
		local thisChangeIndex = changeIndex
		
		if not gui.Enabled then
			background.BackgroundTransparency = 1
			textLabel.TextTransparency = 1
		end
		gui.Parent = playerGui
		gui.Enabled = true
		
		-- Transition message in
		tweenService:Create(background,
			TweenInfo.new(TRANSITION_TIME, Enum.EasingStyle.Quad, Enum.EasingDirection.In),
			{['BackgroundTransparency'] = 0,}
		):Play()
		tweenService:Create(textLabel,
			TweenInfo.new(TRANSITION_TIME, Enum.EasingStyle.Quad, Enum.EasingDirection.In),
			{['TextTransparency'] = 0,}
		):Play()
		
		-- Wait the message duration without yielding
		task.delay(duration or DEFAULT_MESSAGE_DURATION, function()
			if changeIndex == thisChangeIndex then
				
				-- Transition message out
				tweenService:Create(background,
					TweenInfo.new(TRANSITION_TIME, Enum.EasingStyle.Quad, Enum.EasingDirection.Out),
					{['BackgroundTransparency'] = 1,}
				):Play()
				tweenService:Create(textLabel,
					TweenInfo.new(TRANSITION_TIME, Enum.EasingStyle.Quad, Enum.EasingDirection.Out),
					{['TextTransparency'] = 1,}
				):Play()
				
				task.delay(TRANSITION_TIME, function()
					if thisChangeIndex == changeIndex then
						-- Finalize a few things when transition is done
						gui.Enabled = false
						gui.Parent = script
					end
				end)
				
			end
		end)
	end
end


return messageTakeoverModule
