local spieler = FindMetaTable("Player")
util.AddNetworkString("LevelReset")

function spieler:SetLevel(level)
	if(level == nil) then return end
	if(self:GetNWInt("Level", 1) < level) then self:EmitSound("garrysmod/save_load1.wav") end
	local restpunkte = self:GetNWFloat("EXP") - self:GetNWFloat("MAXEXP")
	self:SetNWInt("Level", tonumber(level))
	self:SetPData("Level", tonumber(level))
	self:SetNWFloat("EXP", tonumber(0))
	self:SetPData("EXP", tonumber(0))
	if(restpunkte > 0) then
		self:SetNWFloat("EXP", tonumber(restpunkte))
		self:SetPData("EXP", tonumber(restpunkte))
	end
	self:SetNWFloat("MAXEXP", self:GetNWInt("Level", 1) * 150)
end

function spieler:GiveEXP(zahl)
	if(zahl == nil) then return end
	self:SetPData("EXP", self:GetNWFloat("EXP", 0) + zahl)
	self:SetNWFloat("EXP", self:GetNWFloat("EXP", 0) + zahl)
end

function spieler:Level()
	return self:GetNWInt("Level", 1)
end

function spieler:IsLevel(zahl)
	if(zahl == nil) then return false end
	return self:GetNWInt("Level", 1) >= zahl
end

hook.Remove("PlayerInitialSpawn", "InitializeLeveling")
hook.Add("PlayerInitialSpawn", "InitializeLeveling", function(ply)
	if(ply:GetPData("EXP") == nil) then
		ply:SetPData("EXP", tonumber(0))
		ply:SetPData("Level", tonumber(1))
		ply:SetPData("Level", tonumber(1))
	end
	ply:SetNWInt("Level", tonumber(ply:GetPData("Level")))
	ply:SetNWFloat("EXP", tonumber(ply:GetPData("EXP")))
	ply:SetNWFloat("MAXEXP", tonumber(ply:GetNWInt("Level", 1) * 150))
end)

hook.Remove("PlayerSpawn", "ExtrasLeveling")
hook.Add("PlayerSpawn", "ExtrasLeveling", function(ply)
	timer.Simple(0.5, function()
		ply:SetRunSpeed(ply:GetRunSpeed() + (0.1 * ply:GetNWInt("Level", 1)))
		ply:SetWalkSpeed(ply:GetWalkSpeed() + (0.1 * ply:GetNWInt("Level", 1)))
		ply:SetHealth(ply:Health() + (ply:GetNWInt("Level", 1)))
		ply:SetMaxHealth(ply:GetMaxHealth() + (ply:GetNWInt("Level", 1)))
	end)
end)

hook.Remove("Think", "LevelUp")
hook.Add("Think", "LevelUp", function()
	for _, ply in pairs(player.GetAll()) do
		ply:SetNWFloat("MAXEXP", ply:GetNWInt("Level", 1) * 150)
		if(ply:GetNWFloat("MAXEXP", 150) <= ply:GetNWFloat("EXP", 1)) then
			ply:SetLevel(ply:GetNWFloat("Level", 1) + 1)
		end
	end
end)

hook.Remove("PlayerDeath", "EXPPlayerKill")
hook.Add("PlayerDeath", "EXPPlayerKill", function(victim, inflictor, attacker)
	if(IsValid(attacker)) then
		if(attacker:IsPlayer()) then
			if(victim:Team() == 1) then
			   attacker:GiveEXP(10)
			elseif (victim:Team() == 2) then
			   attacker:GiveEXP(50)
			end
		end
	end
end)


concommand.Add("leveling_adminpanel", function(ply, cmd, args)
	if(ply:IsSuperAdmin()) then
		ply:SendLua([[ LevelingAdminpanel() ]])
	end
end)

net.Receive("LevelReset", function(len, ply)
	if(ply:IsSuperAdmin()) then
		local ausgewaehlterspieler = net.ReadEntity()
		if(IsValid(ausgewaehlterspieler)) then
			ausgewaehlterspieler:SetLevel(1)
		end
	end
end)