--[[ The rest isn't as customizable" ]]
--

debrisS, playerS, datastoreS, gamepassS, marketS = 
game:GetService("Debris"),
game:GetService("Players"),
game:GetService("DataStoreService"),
game:GetService("GamePassService"),
game:GetService("MarketplaceService")

function passedPlayer(p, isLeaving)
	print(p.Name.." has passed")
	local function sendMessage(txt)
		if gameStats["DoMessages?"] then
			local message = Instance.new("Message", p.PlayerGui)
			message.Text = txt
			debrisS:AddItem(message, 2)
		end
	end
	local save, load = 
	function()
		local cDatastore, statStorage = 
		datastoreS:GetDataStore(p.Name.."Stats"),
		p:WaitForChild("PlayerData"):GetChildren()
		for i =  1, #statStorage do
			cDatastore:SetAsync(statStorage[i].Name, statStorage[i].Value)
		end
		sendMessage("Your stats have been saved.")
	end,
	function()
		local cDatastore, stats = 
		datastoreS:GetDataStore(p.Name.."Stats"),
		p:FindFirstChild("PlayerData"):GetChildren()
		for i = 1, #stats do			
			stats[i].Value = cDatastore:GetAsync(stats[i].Name)
		end
		sendMessage("Your stats have been loaded.")
	end
	local chatted = function(c)
		c = c:lower()
		for i, v in pairs(gameStats["DoChat?"]["Keywords"]) do
			if (c == v) then
				save()
			end
		end
	end
	if isLeaving then
		save()
	else
		load()
		if gameStats["DoChat?"]["DoIt?"] then
			p["Chatted"]:connect(chatted)
		end
	end
end

function passTest(p, isLeaving)
	print("Test starting")
	if gameStats["IsAnObby?"] then
		local cAdded = function(c)
			p:LoadCharacter(true)
		end
		p["CharacterAdded"]:connect(cAdded)
	end
	if gameStats.saveType["Normal?"] then
		passedPlayer(p, isLeaving)
	else
		if gameStats.saveType["SavingList?"]["DoIt?"] then
			for i, v in pairs(gameStats.saveType["SavingList?"].theList) do
				if (p.Name == v) then
					passedPlayer(p, isLeaving)
				end
			end
		elseif gameStats.saveType["BestFriends?"] then
			if p:IsBestFriendsWith(game.CreatorId) then
				passedPlayer(p, isLeaving)
			end
		elseif gameStats.saveType["Friends?"] then
			if p:IsFriendsWith(game.CreatorId) then
				passedPlayer(p, isLeaving)
			end
		elseif gameStats.saveType["OwnerOnly?"] then
			if (p.userId == game.CreatorId) then
				passedPlayer(p, isLeaving)
			end
		elseif gameStats.saveType["Gamepass?"]["DoIt?"] then
			if p:PlayerHasPass(p, gameStats.saveType["Gamepass?"]["GamepassId"]) then
				passedPlayer(p, isLeaving)
			end
		elseif gameStats.saveType["Asset/Item?"]["DoIt?"] then
			if p:PlayerOwnsAsset(p, gameStats.saveType["Asset/Item?"]["AssetId"]) then
				passedPlayer(p, isLeaving)
			end
		end
	end
end

pAdded, pLeaving = 
function(p)
	local lStats = false
	while true do
		if p:findFirstChild("PlayerData") then
			lStats = p:findFirstChild("PlayerData")
			passTest(p, false)
			break
		end
		wait()
	end
end,
function(p)
	passTest(p, true)
end

playerS["PlayerAdded"]:connect(pAdded)
playerS["PlayerRemoving"]:connect(pLeaving)