--[[
	MOD/lua/chat.lua [#9529 (#9949), 2053477589]
	Ollie | STEAM_0:0:30709335 <85.23.158.207:27006> | [26.01.14 12:35:15PM]
	===BadFile===
]]

// Coded by Ollie, please don't use without permission :c

if SERVER then
	AddCSLuaFile()

	util.AddNetworkString("PC_ChatPrint")
	
	local meta = FindMetaTable("Player")
	function meta:ChatPrint(text)
		net.Start("PC_ChatPrint")
			net.WriteString(text)
		net.Send(self)
	end

	return
end

if PC then
	if PC.Frame then
		PC.Frame:Remove()
		PC.Frame = nil
	end
end

PC = {}
PC.ChatMessages = {}

surface.CreateFont("PC_Font1",
	{
		font = "Trebuchet MS",
		size = 20,
		weight = 800
	}
)

surface.CreateFont("PC_Font2",
	{
		font = "Trebuchet MS",
		size = 18,
		weight = 800
	}
)

net.Receive("PC_ChatPrint",function()
	LocalPlayer():ChatPrint(net.ReadString() or "")
end)

PC.Tabs = {
	[1] = {
		Name = "Chat",
		BuildPanel = function(pnl)
			pnl.Paint = function(s,w,h)
				//draw.RoundedBox(0,0,0,w,h,Color(0,120,230,150))
			end
			/*
			local PList = vgui.Create("DPanel",pnl)
			PList:EnableVerticalScrollbar(true)
			PList:Dock(FILL)
			*/
			
			PC.PText = vgui.Create("RichText",pnl)
			PC.PText:Dock(FILL)
			PC.PText.Paint = function()
				PC.PText.m_FontName = "PC_Font2"
				PC.PText:SetFontInternal( "PC_Font2" )	
				PC.PText:SetBGColor(Color(0,0,0,0))		
				PC.PText.Paint = nil
			end
			PC.PText:SetVerticalScrollbarEnabled(true)
			
			local tE = vgui.Create("DTextEntry",pnl)
			tE:SetSize(pnl:GetWide(),20)
			tE:Dock(BOTTOM)
			tE:SetMultiline(false)
			tE.OnKeyCodeTyped = function(s,code)
				if code == KEY_ENTER then
					local text = tE:GetText()
					if trim(text) != "" then
						RunConsoleCommand("say",trim(text))
					end
					tE:SetText("")
					PC.Frame:SetVisible(false)
				end
			end
			tE:RequestFocus()
			tE:SetAllowNonAsciiCharacters(true)
			
			PC.tE = tE
		end
	},
	[2] = {
		Name = "Lua",
		BuildPanel = function(pnl)
			pnl.Paint = function(s,w,h)
				//draw.RoundedBox(0,0,0,w,h,Color(255,0,255,125))
			end
			
			local btn = vgui.Create("DButton",pnl)
			btn:SetText("Run script")
			btn:SetPos(0,0)
			btn:SetSize(70,20)
			btn.DoClick = function(s)
				local Menu = DermaMenu()
				
				Menu:AddOption("On myself",function() 
					editor:QueueJavascript("getContents(1);")
				end):SetIcon("icon16/heart.png")
				
				Menu:AddSpacer()
				local sub = Menu:AddSubMenu("On a client")
					for k,v in pairs(player.GetAll()) do
						sub:AddOption(v:Nick(),function()
							editor:QueueJavascript("getContents(2,"..v:EntIndex()..");")
						end):SetIcon("icon16/user.png")
					end
				Menu:AddSpacer()
				Menu:AddOption("On server",function() 
					editor:QueueJavascript("getContents(3);")
				end):SetIcon("icon16/server.png")
				Menu:AddSpacer()
				Menu:AddOption("On all clients",function() 
					editor:QueueJavascript("getContents(4);")
				end):SetIcon("icon16/group.png")
				Menu:Open()
			end	
		
			editor = vgui.Create("DHTML",pnl)
			editor:Dock(FILL)
			editor:DockMargin(0,25,0,0)
			editor:OpenURL("http://ollie.capricorn.seedboxes.cc/ollie/ace/editor.html")
			editor.Code = ""
			editor:AddFunction( "gmod", "RetrieveContents", function(code,id,ply)
				if code and trim(code) != "" then
					editor.Code = trim(code)
					if id == 1 then
						trace = LocalPlayer():GetEyeTraceNoCursor()
						this = trace.Entity
						that = trace.Entity
						there = trace.HitPos
						hitnormal = trace.HitNormal
						here = LocalPlayer():GetPos()
						me = LocalPlayer()
						RunString(editor.Code)
					elseif id == 2 then
						if ply and Entity(ply):IsValid() then
							net.Start("PC_ClientLua")
								net.WriteEntity(Entity(ply))
								net.WriteString(editor.Code)
							net.SendToServer()
						end
					elseif id == 3 then
						net.Start("PC_ServerLua")
							net.WriteString(editor.Code)
						net.SendToServer()
					elseif id == 4 then
						net.Start("PC_ClientsLua")
							net.WriteString(editor.Code)
						net.SendToServer()
					end
				end
			end )
			
		end
	}
}

PC.ActiveTab = 1

function PC.PlayerSay(ply,text,isTeam,dead)

	if PC.PText then
	
		local itm = PC.PText
		local icon = "icon16/user.png"
		
		if ply == NULL then
		
			itm:AppendText("\n")
			itm:InsertColorChange(255,255,255,255)
			itm:AppendText("Console: "..text)
			
			icon = "icon16/world.png"
			table.insert(PC.ChatMessages,
				{{{["plyIcon"] = icon},Color(255,255,255),"Console: "..text},startTime = CurTime()}
			)

		else
		
			local col = team.GetColor(ply:Team())
			
			itm:AppendText("\n")
			itm:InsertColorChange(col.r,col.g,col.b,255)
			itm:AppendText(ply:Nick())
			itm:InsertColorChange(255,255,255,255)
			itm:AppendText(": "..text)
			
			if ply:IsAdmin() then
				icon = "icon16/star.png"
			end
			if ply:GetUserGroup() == "superadmin" then
				icon = "icon16/shield.png"
			end
			
			table.insert(PC.ChatMessages,
				{{{["plyIcon"] = icon},col,ply:Nick(),Color(255,255,255),": "..text},startTime = CurTime()}
			)
			
		end
		
		if ply == NULL then
			print("Console: "..text)
		else
			print(ply:Nick()..": "..text)
		end
	
	end
	
	return true

end
hook.Add("OnPlayerChat","PC.PlayerSay",PC.PlayerSay)

function trim(s)
  return (s:gsub("^%s*(.-)%s*$", "%1"))
end

local meta = FindMetaTable("Player")
function meta:ChatPrint(text)
	chat.AddText(Color(255,255,255),text)
end

function chat.AddText(...)
	local itm = PC.PText
	
	itm:AppendText("\n")
	for k,v in pairs({...}) do
		if type(v) == "table" then
			if v.r then
				itm:InsertColorChange(v.r,v.g,v.b,255)
			end
		elseif type(v) == "Player" then
			itm:AppendText(v:Nick())
			Msg(tostring(v:Nick()) or "")
		else
			itm:AppendText(tostring(v) or "")
			Msg(tostring(v) or "")
		end
	end
	Msg("\n")

	table.insert(PC.ChatMessages,
		{{unpack({...})},startTime = CurTime()}
	)
end

function PC.PaintChat()
	if !PC.Frame then return end
	
	if PC.Frame:IsVisible() == false then
	
		surface.SetFont("PC_Font1")
		
		local toRemove = {}

		local order = #PC.ChatMessages
		for i=1,#PC.ChatMessages do
			local m = order-i
		
			local item = PC.ChatMessages[i]
		
			local startTime = item["startTime"]
			local alpha = 255 - 255*(CurTime()-startTime)/10
			if alpha < 0 then alpha = 0 end
		
			local offset = 0
			local color = Color(255,255,255)
			
			for k,v in pairs(item[1]) do
			
				if type(v) == "string" then
					draw.SimpleTextOutlined(v,"PC_Font1",10 + offset,ScrH()-250-m*20,color,TEXT_ALIGN_LEFT,TEXT_ALIGN_TOP,1,Color(0,0,0,alpha))
					local x,y = surface.GetTextSize(v)
					offset = offset + x
				elseif type(v) == "table" then
					if v.plyIcon != nil then
						surface.SetMaterial(Material(v.plyIcon))
						surface.SetDrawColor(255,255,255,alpha)
						surface.DrawTexturedRect(10 + offset,ScrH()-250-m*20 - 18,16,16)
						offset = offset + 20
					elseif v.r then
						local r,g,b = v.r,v.g,v.b
						color = Color(r,g,b,alpha)
					end
				elseif v:IsPlayer() then
					draw.SimpleTextOutlined(v:Nick(),"PC_Font1",10 + offset,ScrH()-250-m*20,color,TEXT_ALIGN_LEFT,TEXT_ALIGN_TOP,1,Color(0,0,0,alpha))
					local x,y = surface.GetTextSize(v:Nick())
					offset = offset + x
				end
			
			end
		
			if alpha == 0 then
				table.insert(toRemove,i)
			end
		
		end
		
		for k,v in pairs(toRemove) do
			table.remove(PC.ChatMessages,v)
		end
	
	end
	
end
hook.Add("HUDPaint","PC.PaintChat",PC.PaintChat)

function PC.OpenChat()

	if !PC.Frame then

		PC.Frame = vgui.Create("DFrame")
		PC.Frame:SetSize(500,300)
		PC.Frame:SetPos(10,ScrH()-450)
		PC.Frame:MakePopup()
		PC.Frame:SetDraggable(true)
		PC.Frame:SetTitle("")
		PC.Frame:SetSizable(true)
		PC.Frame:ShowCloseButton(false)
	
		PC.Frame.Paint = function(s,w,h)
			draw.RoundedBox(0,0,0,w,h,Color(20,60,95,235))
		end
		
		local Close = vgui.Create("DButton",PC.Frame)
		Close:SetText("")
		Close:SetSize(20,20)
		Close:SetPos(PC.Frame:GetWide()-30,10)
		Close.DoClick = function() PC.Frame:SetVisible(false) end
		Close.Paint = function(s,w,h)
			//draw.RoundedBox(0,0,0,w,h,Color(255,255,255))
			draw.SimpleTextOutlined("X","PC_Font1",w/2,h/2,Color(255,255,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER,1,Color(0,0,0))
		end
		
		PC.Frame.PerformLayout  = function(s)
			Close:SetPos(PC.Frame:GetWide()-30,10)
		end
		
		for c=1,#PC.Tabs do
			v = PC.Tabs[c]
			
			local panel = vgui.Create("DPanel",PC.Frame)
			panel:Dock(FILL)
			panel:DockMargin(5,5,5,5)
			
			v.BuildPanel(panel)
			v.Panel = panel
			v.Panel.ID = c
			
			if c > 1 then
				panel:SetVisible(false)
			end
			
			local btn = vgui.Create("DButton",PC.Frame)
			btn:SetText("")
			btn:SetSize(80,20)
			btn:SetPos(10 + (c-1)*80,10)
			btn.ID = c
			btn.Name = v.Name
			btn.DoClick = function(s)
				for k,v in pairs(PC.Tabs) do
					if s.ID == k then
						v.Panel:SetVisible(true)
					else
						v.Panel:SetVisible(false)
					end
				end
				PC.ActiveTab = s.ID
			end
			btn.Paint = function(s,w,h)
				draw.RoundedBox(0,0,0,w,h,PC.ActiveTab == s.ID and Color(255,255,255) or Color(155,155,155))
				draw.SimpleTextOutlined(s.Name,"PC_Font1",w/2,h/2,Color(255,255,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER,1,Color(0,0,0))
			end
		
		end
		
	else
		
		PC.Frame:SetVisible(true)
		//PC.tE:RequestFocus()
	
	end
	
end

timer.Simple(0.01,function()
	PC.OpenChat()
	PC.Frame:SetVisible(false)
end)

function PC.SuppressBind(pl, bind, pressed)
    if pressed and string.find(bind, "messagemode") then
	
		PC.OpenChat()
		
        return true
    end
end
hook.Add("PlayerBindPress", "JChat.PlayerBindPress", PC.SuppressBind)

hook.Add("StartChat","PC.Start",function()
	return true
end)

hook.Add("HUDShouldDraw", "PC.HUDShouldDraw", function(obj)
	if obj == "CHudChat" then
		return false
	end
end)


print("Loaded Precision Chat!")