if not SERVER then return end
zrmine = zrmine or {}
zrmine.data = zrmine.data or {}

function zrmine.data.DataChanged(ply)
	if not ply.zrms_DataChanged then
		ply.zrms_DataChanged = true
	end
end

function zrmine.data.CreateDir()
	timer.Create("zrms_XP", zrmine.config.Pickaxe_LvlSys_SaveTime, 0, function()
		for k, v in pairs(player.GetAll()) do
			if (v.zrms_DataChanged) then
				v:SetPData("zrmine/XP/database", util.TableToJSON(v.zrms))
				v.zrms_DataChanged = false
			end
		end
	end)
end

hook.Add("InitPostEntity", "zrmine.xp.CreateDir_id", zrmine.data.CreateDir)

function zrmine.data.PlayerDisconnect(ply)
	if (ply.zrms_DataChanged) then
		ply:SetPData("zrmine/XP/database", util.TableToJSON(ply.zrms))
	end
end

hook.Add("PlayerDisconnected", "zrmine.xp.playerdisconnect_id", zrmine.data.PlayerDisconnect)

function zrmine.data.PlayerSpawn(ply)
	timer.Create("Steam_id_delay_zrms" .. ply:EntIndex(), 1, 1, function()
		if (IsValid(ply)) then
			local convert = util.JSONToTable(ply:GetPData("zrmine/XP/database", ""))
			ply.zrms = {}

			if (convert ~= nil) then
				ply.zrms = convert
			else
				ply.zrms = {
					xp = 0,
					lvl = 0
				}
			end

			zrmine.data.DataChanged(ply)
		end
	end)
end

hook.Add("PlayerInitialSpawn", "zrmine.xp.playerspawn_id", zrmine.data.PlayerSpawn)
