-- Returns a string key to use in order to access a player's data store

local function getKey(player)
	return tostring(player.UserId)
end

local function plural(n)
	return n == 1 and "" or "s"
end

local function getTimeString(seconds)
	local minutes = math.floor(seconds / 60)
	seconds = seconds % 60
	local hours = math.floor(minutes / 60)
	minutes = minutes % 60
	local days = math.floor(hours / 24)
	hours = hours % 24
	local s
	if days > 0 then
		s = days .. " day" .. plural(days)
		if hours > 0 then
			s = s .. ", " .. hours .. " hour" .. plural(hours)
		end
	elseif hours > 0 then
		s = hours .. " hour" .. plural(hours)
		if minutes > 0 then
			s = s .. ", " .. minutes .. " minute" .. plural(minutes)
		end
	elseif minutes > 0 then
		s = minutes .. " minute" .. plural(minutes)
		if seconds > 0 then
			s = s .. ", " .. seconds .. " second" .. plural(seconds)
		end
	else
		s = seconds .. " second" .. plural(seconds)
	end
	return s
end

local function processPayload(player, payload)
	local now = os.time()
	if payload["status"] == "banned" then
		local kickMessage = ""
		if type(payload["expires"]) == "number" then
			if now >= payload["expires"] then
				-- Ban expired
				return
			end
			local seconds = math.max(0, payload["expires"] - now)
			-- Double check
			if seconds <= 0 then return end
			kickMessage = MESSAGE_BAN:gsub("%%TIME%%", getTimeString(seconds))
		else
			kickMessage = MESSAGE_BAN_NO_EXPIRE
		end
		if type(payload["reason"]) == "string" then
			kickMessage = kickMessage .. REASON:gsub("%%REASON%%", payload["reason"])
		end
		script.KickingBannedPlayer:Fire(player, payload)
		-- Attempt to increment the number of "kicks"
		spawn(function ()
			pcall(function ()
				dsPlayerBans:UpdateAsync(getKey(player), function (oldPayload)
					if not oldPayload then return nil end
					-- Shallow copy
					local newPayload = {}
					for k, v in pairs(oldPayload) do newPayload[k] = v end
					-- Increment # of kicsk 
					newPayload["kicks"] = (newPayload["kicks"] or 0) + 1
					newPayload["lastKick"] = now
					return newPayload
				end)
			end)
		end)
		--local Controls = require(player.PlayerScripts:WaitForChild("PlayerModule")):GetControls()---GetControls

		--Controls:Disable() 
		wait(3)
		player.PlayerGui.MainUI.Banished.LocalScript.Disabled = false
		player.PlayerGui.MainUI.Banished.Banned.Visible = true
	end
end

local function onPlayerAdded(player)
	local payload
	pcall(function () payload = dsPlayerBans:GetAsync(getKey(player)) end)
	if type(payload) == "table" then
		processPayload(player, payload)
	else
		-- No bans
	end
end

Players.PlayerAdded:connect(onPlayerAdded)
for _, player in pairs(Players:GetPlayers()) do
	onPlayerAdded(player)
end
