--[[
	gcdebugger.lua
	DrogenViech | (STEAM_0:0:8615861)
	===DStream===
]]

local collectgarbage=collectgarbage
local ScrW=ScrW
local Round=math.Round
local surface=surface or math
local draw=draw or math

local DrawRect=surface.DrawRect
local SetDrawColor=surface.SetDrawColor
local SimpleText=draw.SimpleText
local TEXT_ALIGN_CENTER=TEXT_ALIGN_CENTER
local SetFont=surface.SetFont
local SetTextPos=surface.SetTextPos
local SetTextColor=surface.SetTextColor
local GetTextSize=surface.GetTextSize
local DrawText=surface.DrawText

if SERVER then
	local times=0
    hook.Add('Think',1,function() 
		umsg.Start("GC")
			umsg.Float(collectgarbage"count")
		umsg.End()
		
		if times==0 then return end
		
		for i=1,times do
			collectgarbage"step"
		end
		
    end)

	function SetGC(n)
		times=tonumber(n) or times
	end
    return
end

local kb_s
usermessage.Hook("GC",function( umsg ) 
    kb_s=umsg:ReadFloat()
end)

local max1,max2=16,16
local col=Color(255,255,255,255)
local PAINT=function(pnl)
	local W=pnl and pnl:GetWide() or ScrW()
    local oy=1
    
    local kb=collectgarbage"count"
    SetDrawColor(0,0,0,100)
    DrawRect(0,oy,W,10)
    SetDrawColor(0,0,255,100)
	
    local frac=(kb/1024)
    
    
    max1=max1<frac and frac or max1
    DrawRect(0,oy,W*(frac/max1),10)
    local txt=(Round(kb/1024)).." MB"
    
    SetFont"Trebuchet18"
	SetTextColor(255,255,255,255)
	local w,h=GetTextSize(txt)
	SetTextPos( W*(frac/max1)-w*0.5 ,oy-h*0.20)
	DrawText(txt)

    oy=12
    
	if not kb_s then return end
	
    kb=kb_s
    SetDrawColor(0,0,0,100)
    DrawRect(0,oy,W,10)
    SetDrawColor(200,50,50,100)
	
    frac=(kb/1024)
    
    max2=max2<frac and frac or max2
    
    DrawRect(0,oy,W*(frac/max2),10)
    txt=(Round(kb/1024*100)/100).." MB"
	
	local w,h=GetTextSize(txt)
	SetTextPos( W*(frac/max2)-w*0.5 ,oy-h*0.20)
	DrawText(txt)
	
end

if ValidPanel(_G.GCVIS) then
	_G.GCVIS:Remove()
	_G.GCVIS=nil
end
_G.GCVIS=vgui.Create'EditablePanel'
local a=_G.GCVIS

a:SetSize(ScrW(),64-10)
a:SetPos(0,ScrH()-12)
a:SetVisible(true)
a.Paint=PAINT
function a:OnMouseReleased(mc)
	if mc==MOUSE_RIGHT then self:Remove() end
--	if times==0 then hook.Remove("Think","GC") end
end

local times=0
hook.Add("Think","GC",function() 
	if times==0 then return end
	for i=1,times do
		collectgarbage"step"
	end
end)

local w=vgui.Create('DNumberWang',a)
w:SetMin(0)
w:SetMax(4000)
w:SetPos(10,-4)--a:GetTall()-w:GetTall())
w:SetWide(100)
function w:OnValueChanged()
	local num = math.Round(w:GetValue())
	times=num	
end

function SetGC(n)
	times=tonumber(n) or times
	w:SetValue(times)
end
