if PrP and PrP.CleanUp then PrP.CleanUp() end

local EMPTYTABLE = {}
local NWSHOW_ALWAYS = 1
local NWSHOW_TRUE = 2
local NWSHOW_FALSE = 3

PrP = {}
PrP.SomeString = "LaLiLuLeLo"
PrP.PrefixString = "prpdev_"

PrP.Config = {
	HeadCross = true,
	HeadCrossSize = 12,
	TeamBased = false,
	AimForTeam = true,
	SnapDeadPlayers = true,
	SnapPlayerFromVehicle = true,
	ESPAlpha = 200,
	ESPDefColor = Color(100,64,128,255),
	ESPFont = "UiBold",
	ESPRect = 64,
	DisplayHealth = true,
	DisplayTeam = true,
	AimVelocityLagMult = 0.2,
	NWBools = EMPTYTABLE
}

PrP.GamemodeConfig = {} -- Lowercase names
PrP.GamemodeConfig.sandbox = {}
PrP.GamemodeConfig.noxbox2 = PrP.GamemodeConfig.sandbox
PrP.GamemodeConfig.darkrp = {}
PrP.GamemodeConfig.bestdarkrp = PrP.GamemodeConfig.darkrp
PrP.GamemodeConfig.terrortown = {NWBools = {disguised = NWSHOW_TRUE, found = NWSHOW_TRUE}}

local cvar2,thehero
local emptyfunc = function() end
local dinfox,dinfoy,dinfoa = 0,0,255

PrP.Attachments = {
	"forward",
	"eyes",
}

PrP.CoolCVars = {
	"sv_cheats",
	"host_timescale",
	"sv_scriptenforcer",
	"lua_openscript_cl",
	"lua_run_cl",
}

PrP.CVarFunctions = {
	"CreateConVar",
	"CreateClientConVar",
	"GetConVar",
}

PrP.Hooks = {}
PrP.ShootPos = {}
PrP.ShootPos2Screen = {}
PrP.ShootPosLag = {}
PrP.ShootPosLag2Screen = {}
PrP.Target = NULL

function PrP.CleanUp()
	for _,t in ipairs(PrP.Hooks) do hook.Remove(t.hn, t.ui) end
end

function PrP.SafeCVarChange(cvar, value)
	if not PrP.CheckForModules() then return end
	local oldcvarchanged = cvars.OnConVarChanged
	cvars.OnConVarChanged = emptyfunc
	cvar2.SetValue(cvar, value)
	cvars.OnConVarChanged = oldcvarchanged
end

function PrP.Message(msg)
	if not thehero then MsgN(msg) end
	thehero:PrintMessage(HUD_PRINTTALK, msg)
end

function PrP.CheckForModules(silent)
	if cvar2 then
		return true
	elseif not silent then
		PrP.Message("You need to load the modules to use this function.\nThey are not loaded on start because loading them can crash GMod.")
	end
end

function PrP.CanTarget(ent)
	return ent:IsPlayer()
end

function PrP.DrawPlayerInfo(text,r,g,b)
	surface.SetFont(PrP.Config.ESPFont)
	surface.SetTextPos(dinfox,dinfoy)
	surface.SetTextColor(r,g,b,dinfoa)
	surface.DrawText(text)

	local width,height = surface.GetTextSize(text)
	dinfoy = dinfoy + height
end

function PrP.DrawPlayerInfoReset(x,y,a)
	dinfox = x
	dinfoy = y
	dinfoa = a
end

function PrP.CreateHook(h,u,f)
	table.insert(PrP.Hooks, {hn = h, ui = u})
	hook.Add(h,u,f)
end

PrP.CreateHook("CalcView", PrP.SomeString .. "v", function(ply,orig,ang,afov)
	local view = {origin = orig, angles = ang, fov = afov}
	if PrP.Freeview and PrP.FreeviewAng and PrP.FreeviewPos then
		view.origin = PrP.FreeviewPos
		view.angles = PrP.FreeviewAng
	end
	return view
end)

PrP.CreateHook("InputMouseApply", PrP.SomeString .. "a", function(cmd, x, y, angle)
	local sens = GetConVar("sensitivity"):GetInt()*0.005
	if PrP.Freeview then
		if not PrP.FreeviewAng then
			PrP.FreeviewAng = angle
		end
		PrP.FreeviewAng.yaw = PrP.FreeviewAng.yaw - x*sens
		PrP.FreeviewAng.pitch = PrP.FreeviewAng.pitch + y*sens
		return true
	end
end)

PrP.CreateHook("CreateMove", PrP.SomeString .. "m", function(move)
	if PrP.Freeview then
		if not PrP.FreeviewPos then PrP.FreeviewPos = thehero:GetShootPos() end
		
		local posmod = Vector(0,0,0)
		if thehero:KeyDown(IN_FORWARD) then
			posmod = posmod + PrP.FreeviewAng:Forward()
		elseif thehero:KeyDown(IN_BACK) then
			posmod = posmod - PrP.FreeviewAng:Forward()
		end
		if thehero:KeyDown(IN_MOVERIGHT) then
			posmod = posmod + PrP.FreeviewAng:Right()
		elseif thehero:KeyDown(IN_MOVELEFT) then
			posmod = posmod - PrP.FreeviewAng:Right()
		end
		
		posmod = posmod * 2
		
		--local sprint = thehero:KeyDown(IN_SPEED)
		--local duck = thehero:KeyDown(IN_DUCK)
		
		local sprint = input.IsKeyDown(KEY_LSHIFT)
		local duck = input.IsKeyDown(KEY_LCONTROL)
		
		if sprint and duck then
			posmod = posmod * 10
		elseif sprint then
			posmod = posmod * 4
		elseif duck then
			posmod = posmod * 0.25
		end
		
		PrP.FreeviewPos = PrP.FreeviewPos + posmod

		--[[
		local butts = move:GetButtons()
		if butts & IN_DUCK ~= 0 then butts = butts - IN_DUCK end
		if butts & IN_SPEED ~= 0 then butts = butts - IN_SPEED end
		move:SetButtons(butts)
		]]--
		move:SetForwardMove(0)
		move:SetSideMove(0)
		move:SetUpMove(0)
	end
	
	local target = PrP.Target
	local isply = target:IsPlayer()
	if target:IsValid() then
		if PrP.ShootPosLag[target] and ((isply and (PrP.Config.SnapDeadPlayers or target:Alive())) or (not isply and target:IsValid())) then
			move:SetViewAngles((PrP.ShootPosLag[target] - thehero:GetShootPos()):Angle())
		else
			PrP.Target = NULL
		end
	end
end)

local initname = PrP.SomeString .. "i"
PrP.CreateHook("Think", initname, function()
	local lp = LocalPlayer()
	if not lp:IsPlayer() then return end
	
	hook.Remove("Think", initname)
	initname = nil
	
	thehero = lp
	PrP.Width = ScrW()
	PrP.WidthH = PrP.Width/2
	PrP.Height = ScrH()
	PrP.HeightH = PrP.Height/2
	
	local gmfolder = string.lower(GAMEMODE.FolderName)
	if PrP.GamemodeConfig and PrP.GamemodeConfig[gmfolder] then
		for k,v in pairs(PrP.GamemodeConfig[gmfolder]) do
			PrP.Config[k] = v
		end
	end
end)

PrP.CreateHook("ShouldDrawLocalPlayer", PrP.SomeString .. "l", function()
	if PrP.Freeview then return true end
end)

PrP.CreateHook("Think", PrP.SomeString .. "t", function()
	if not thehero then return end
	
	local realpga = player.GetAll()
	if not PrP.RealPGA or #realpga ~= #PrP.RealPGA then
		PrP.RealPGA = realpga
		local pga = {}
		for k,v in ipairs(realpga) do
			if v ~= thehero then
				table.insert(pga, v)
			end
		end
		PrP.NoLocalPGA = pga
	end
	
	for _,ply in ipairs(PrP.NoLocalPGA) do
		local shootpos
		for _,attachment in ipairs(PrP.Attachments) do
			local myattachid = ply:LookupAttachment(attachment)
			if myattachid then
				local myattach = ply:GetAttachment(myattachid)
				if myattach and myattach.Pos then
					shootpos = myattach.Pos
					break
				end
			end
		end
		if not shootpos then
			shootpos = ply:GetPos() + ply:OBBCenter()
		end
		PrP.ShootPos[ply] = shootpos
		PrP.ShootPos2Screen[ply] = shootpos:ToScreen()
		PrP.ShootPosLag[ply] = shootpos + ply:GetVelocity():Normalize() * (ply:Ping() * FrameTime() * PrP.Config.AimVelocityLagMult)
		PrP.ShootPosLag2Screen[ply] = PrP.ShootPosLag[ply]:ToScreen()
	end
	
	local realega = ents.GetAll()
	if not PrP.RealEGA or #realega ~= #PrP.RealEGA then
		PrP.RealEGA = realega
		local ega = {}
		for k,v in ipairs(ents.GetAll()) do
			local add = true
			for kk,vv in ipairs(realpga) do
				if v == vv then
					add = false
					break
				end
			end
			if add then
				table.insert(ega,v)
			end
		end
		PrP.NoPlayerEGA = ega
	end
	
	if PrP.Seeking and not PrP.Target:IsValid() then
		local localtrace = thehero:GetEyeTrace()
		if PrP.CanTarget(localtrace.Entity) then
			PrP.Target = localtrace.Entity
		elseif PrP.Config.SnapPlayerFromVehicle and localtrace.Entity:IsVehicle() then
			for _,ply in ipairs(PrP.NoLocalPGA) do
				if ply:GetVehicle() == localtrace.Entity then
					PrP.Target = ply
					break
				end
			end
		end
		
		if not PrP.Target:IsValid() then
			local pickentity = NULL
			local pickdistance = PrP.Config.HeadCrossSize
			for ply,pos in pairs(PrP.ShootPos2Screen) do
				local dist = math.Distance(PrP.WidthH, PrP.HeightH, pos.x, pos.y)
				if dist < pickdistance then pickdistance = dist pickentity = ply end
			end
			if PrP.CanTarget(pickentity) then PrP.Target = pickentity end
		end
	end
end)

PrP.CreateHook("HUDPaint", PrP.SomeString .. "p", function()
	if not thehero then return end
	local curtime = CurTime()
	local ctdec = curtime - math.floor(curtime)
	local myteam = thehero:Team()
	local sin = math.abs(math.sin(curtime*3))
	local sin2 = math.abs(math.sin(curtime*4 + 2))
	local sin3 = math.abs(math.sin(curtime*5 + 7))
	
	for ent,posonscreen in pairs(PrP.ShootPos2Screen) do
		if not ent:IsValid() then
			PrP.ShootPos[ent] = nil
			PrP.ShootPos2Screen[ent] = nil
		else
			local halfsize = PrP.Config.HeadCrossSize
			local fullsize = halfsize * 2
			
			local posonscreenlag = PrP.ShootPosLag2Screen[ply]
			if PrP.Target == ent and posonscreenlag then
				surface.SetDrawColor(255,0,0,128)
				surface.DrawRect(posonscreenlag.x - 5, posonscreenlag.y - 5, 10, 10)
			end
			
			local pos = ent:GetPos()
			local dist = pos:Distance(thehero)
			local movetype = ent:GetMoveType()
			local health = ent:Health()
			
			local entteam,isphysical,isalive,isply,name,color,namecol,admin,teamcol,teamname
			if ent:IsPlayer() then
				entteam = ent:Team()
				teamcol = team.GetColor(entteam)
				teamname = team.GetName(entteam)
				isalive = ent:Alive()
				isply = true
				isphysical = isalive and (movetype == MOVETYPE_WALK or movetype == MOVETYPE_NOCLIP)
				name = ent:GetName()
				admin = ent:IsAdmin()
				if PrP.Config.TeamBased then
					if myteam == entteam then
						color = Color(0,255,0,255)
					else
						color = Color(255,0,0,255)
					end
				else
					if teamcol.r*0.75 + teamcol.g*0.75 + teamcol.b < 255 then
						color = Color(255 - teamcol.r, 255 - teamcol.g, 255 - teamcol.b, 255)
					else
						color = teamcol
					end
				end
				namecol = color
				if admin then
					namecol = Color(namecol.r * sin, namecol.g * sin2, namecol.b * sin3, namecol.a)
				end
			else
				name = ent:GetClass()
			end
			
			local alpha = PrP.Config.ESPAlpha
			
			surface.SetDrawColor(color.r, color.g, color.b, alpha)
			surface.DrawOutlinedRect(posonscreen.x - halfsize, posonscreen.y - halfsize, fullsize, fullsize)
			surface.SetDrawColor(color.r, color.g, color.b, alpha*0.2)
			surface.DrawOutlinedRect(posonscreen.x - halfsize-1, posonscreen.y - halfsize-1, fullsize+2, fullsize+2)
			
			PrP.DrawPlayerInfoReset(posonscreen.x + halfsize + 3, posonscreen.y - halfsize, alpha)
			PrP.DrawPlayerInfo(name, namecol.r, namecol.g, namecol.b)
			if PrP.Config.DisplayHealth then
				if isalive then
					PrP.DrawPlayerInfo("HP: " .. health, color.r, color.g, color.b)
				else
					PrP.DrawPlayerInfo("- DEAD -", 64, 64, 64)
				end
			end
			if PrP.Config.DisplayTeam and entteam then
				PrP.DrawPlayerInfo("Team: " .. teamname, teamcol.r, teamcol.g, teamcol.b)
			end
			for nwvar,displaytype in pairs(PrP.Config.NWBools) do
				local bool = ent:GetNWBool(nwvar, false)
				if displaytype == NWSHOW_ALWAYS or (bool and displaytype == NWSHOW_TRUE) or (not bool and displaytype == NWSHOW_FALSE) then
					PrP.DrawPlayerInfo("NWBool " .. nwvar, teamcol.r, teamcol.g/2, teamcol.b/2)
				end
			end
		end
	end
	
	if PrP.Freeview then
		if type(PrP.Freeview) == "number" and PrP.Freeview + 3 < CurTime() then
			PrP.Freeview = true
			PrP.Message("Locked Freeview. Use the freeview bind to unlock it.")
		end
		local mpos = thehero:GetPos():ToScreen()
		PrP.DrawPlayerInfoReset(mpos.x + 5, mpos.y, 200)
		PrP.DrawPlayerInfo("<- You", 255, 0, 0)
	end
end)

concommand.Add(PrP.PrefixString .. "getgamemodefolder", function()
	PrP.Message(GAMEMODE.FolderName)
end)

concommand.Add(PrP.PrefixString .. "cleanup", function()
	PrP.CleanUp()
end)

concommand.Add(PrP.PrefixString .. "listmodels", function()
	local models = {}
	for _,ent in ipairs(ents.GetAll()) do local model = ent:GetModel() if model then models[model] = true end end
	for model,_ in pairs(models) do print(model) end
end)

function PrP.LoadModules(allowload)
	if cvar2 then MsgN("CVar2 is already loaded.") return end
	if LARGE then MsgN("CVar2 was preloaded. Activating.") cvar2 = LARGE return end
	if not allowload then MsgN("CVar2 isn't loaded. Use '" .. PrP.PrefixString .. "modules 1' to load it.") end
	MsgN("Loading CVar2...")
	require("cvar2")
end
concommand.Add(PrP.PrefixString .. "modules", function(_,_,a)
	PrP.LoadModules(tobool(a[1]))
end)
PrP.LoadModules(false)

concommand.Add("+" .. PrP.PrefixString .. "sonic", function(_,_,a)
	PrP.SafeCVarChange("sv_cheats", 1)
	PrP.SafeCVarChange("host_timescale", tonumber(a[1]) or 1)
end)

concommand.Add("-" .. PrP.PrefixString .. "sonic", function()
	PrP.SafeCVarChange("host_timescale", 1)
	PrP.SafeCVarChange("sv_cheats", 0)
end)

concommand.Add("+" .. PrP.PrefixString .. "seek", function() PrP.Seeking = true end)
concommand.Add("-" .. PrP.PrefixString .. "seek", function() PrP.Seeking = false PrP.Target = NULL end)

concommand.Add("+" .. PrP.PrefixString .. "freeview", function()
	if not PrP.Freeview then
		PrP.Freeview = CurTime()
		PrP.FreeviewAng = nil
		PrP.FreeviewPos = nil
	else
		PrP.Freeview = false
	end
end)
concommand.Add("-" .. PrP.PrefixString .. "freeview", function()
	if type(PrP.Freeview) == "number" then
		PrP.Freeview = false
	end
end)
