-- How long it should take before all players data saves on a timer.
epsilonScript.Config:Set( SERVER, "SaveTimer", 300 );

require( "glon" );

-- Function to load the players data.
function epsilonScript.LoadPlayer( ply )
	ply.epsilonScriptData = {};
	ply.DoorData = {};
	ply.Ready = false;
	ply:SetNWString( "RPName", "" );
	
	timer.Simple( 10, function()
		umsg.Start( "PISUM", ply )
		umsg.End()
	end, ply );
	
	if ( file.Exists( "epsilonScript/PlayerData/" .. epsilonScript.Config:Get( "ActiveScheme" ) .. "/" .. ply:GetFormattedSteamid() .. ".txt" ) ) then
		local Data = glon.decode( file.Read( "epsilonScript/PlayerData/" .. epsilonScript.Config:Get( "ActiveScheme" ) .. "/" .. ply:GetFormattedSteamid() .. ".txt" ) );
		
		if ( Data == nil or Data == "" ) then
			timer.Simple( 10, function()
				ply:ConCommand( "eps_Createnewcharmenu" );
			end, ply );
		else
			timer.Simple( 10, function()
				ply.epsilonScriptData = Data;
				ply:ConCommand( "eps_startselectchar" );
			end, ply );
		end
	else
		timer.Simple( 10, function()
			ply:ConCommand( "eps_Createnewcharmenu" );
		end, ply );
	end;
end;

-- Function to save a players data.
function epsilonScript.SavePlayer( ply )
	if ( !ply.Ready ) then
		return;
	end;
	
	local Data = glon.encode( ply.epsilonScriptData );
	file.Write( "epsilonScript/PlayerData/" .. epsilonScript.Config:Get( "ActiveScheme" ) .. "/" .. ply:GetFormattedSteamid() .. ".txt", Data );
end;

-- A timer that saves all players data each < Config Time >.
timer.Create( "SaveAllPlayers", epsilonScript.Config:Get( "SaveTimer" ), 0, function()
	for k, v in pairs( player.GetAll() ) do
		if ( v:IsValid() ) then
			epsilonScript.SavePlayer( v );
			v:SendNotify( "Your character data has been saved!" );
		end;
	end;
end );

-- Help function to return data from the players data table.
function _R.Player:GetCharInfo( data )
	if ( self.epsilonScriptData[ self.CharID ][ data ] ) then
		return self.epsilonScriptData[ self.CharID ][ data ]
	end
end

-- Help function to set a field in the players data table.
function _R.Player:SetCharInfo( field, data )
	if ( self.epsilonScriptData[ self.CharID ][ field ] ) then
		self.epsilonScriptData[ self.CharID ][ field ] = data;
	else
		Error( "Field '" .. field .. "' doesn't exist!" );
	end;
end;

function _R.Player:GetFormattedSteamid()
	local Formatted = string.gsub( self:SteamID(), "STEAM", "" );
	Formatted = string.gsub( Formatted, ":", "" );
	Formatted = string.gsub( Formatted, "_", "" );
	
	return Formatted;
end;
