--//Settings\-- 

local Save_Wait_Time = 60 
local Auto_Save = true 
local Save_On_Leave = true 

function onPlayerEntered(newPlayer) 
	local datafolder = Instance.new("Folder") 
	datafolder.Parent = DataFolder 
	datafolder.Name = newPlayer.UserId 
	local DataValue = DataFolder.Data:clone() 
	DataValue.Parent = DataFolder[newPlayer.UserId] 
	local Data = DataValue:GetChildren() 
	local DataTable = {} 
	for i=1,#Data do 
		local n = Data[i].Name 
		DataTable[n] = Data[i].Value 
	end 
	--GetData--
	local DataStore = DataStoreService:GetDataStore(newPlayer.userId) 
	if DataStore:GetAsync("Save") == nil then 
		local succeed, errormsg = pcall(function()
			DataStore:SetAsync("Save", DataTable) 
		end) 
		if succeed then 
			print("Data saved correctly") 
		else 
			print("Error: ".. errormsg) 
		end 
	end 

	local succeed, errormsg = pcall(function() 
		DataTable = DataStore:GetAsync("Save") 
	end) 
	if succeed then 
		print("Data received correctly") 
	else 
		print("Error: ".. errormsg) 
	end 
	--LoadData-- 
	local DataToLoad = DataValue:GetChildren() 
	for i=1,#DataToLoad do 
		local n = DataToLoad[i].Name 
		if DataTable[n] ~= nil then 
			DataToLoad[i].Value = DataTable[n] 
		end 
	end 
end 

game.Players.PlayerAdded:connect(onPlayerEntered) 

if Save_On_Leave then 
	game.Players.PlayerRemoving:connect(function(Player) 
		--SaveData-- 
		local DataStore = DataStoreService:GetDataStore(Player.userId) 
		local Data = DataFolder[Player.UserId].Data:GetChildren() 
		local DataTable = {} 
		for i=1,#Data do 
			local n = Data[i].Name 
			DataTable[n] = Data[i].Value 
		end 
		local succeed, errormsg = pcall(function() 
			DataStore:SetAsync("Save", DataTable) 
		end) 
		if succeed then 
			print("Data saved correctly") 
		else 
			print("Error: ".. errormsg) 
		end 
		DataFolder[Player.UserId]:Destroy() 
	end)
end 

local DataSaveTable = {} 

if Auto_Save == true then 
	while wait(1) do 
		for _, Player in pairs(game.Players:GetPlayers()) do
			if not DataSaveTable[Player] then 
				DataSaveTable[Player] = tick() 
			elseif tick() - DataSaveTable[Player] >= Save_Wait_Time then 
				print("Saved") 
				DataSaveTable[Player] = tick() 
				local DataStore = DataStoreService:GetDataStore(Player.userId) 
				local Data = DataFolder[Player.UserId].Data:GetChildren() 
				local DataTable = {} 
				for i=1,#Data do 
					local n = Data[i].Name 
					DataTable[n] = Data[i].Value 
				end 
				local succeed, errormsg = pcall(function() 
					DataStore:SetAsync("Save", DataTable) 
				end) 
				if succeed then 
					print("Data saved correctly") 
				else 
					print("Error: "..errormsg) 
				end 
			end 
		end 
	end 
end
