require("oosocks")

local errcodes = {
	[SCKERR_OK] = "SCKERR_OK",
	[SCKERR_BAD] = "SCKERR_BAD",
	[SCKERR_CONNECTION_RESET] = "SCKERR_CONNECTION_RESET",
	[SCKERR_NOT_CONNECTED] = "SCKERR_NOT_CONNECTED",
	[SCKERR_TIMED_OUT] = "SCKERR_TIMED_OUT",
}

hex2str = {[0]="0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}

local function GetCharHex(char)
	local dec,dec2 = string.byte(char or " ")
	if dec == 0 then return "0" end
	local rem = dec
	local hexstr = ""
	while (rem ~= 0) do
		hexstr = hex2str[rem%16] .. hexstr
		rem = math.floor(rem/16)
	end
	return hexstr
end

local function HexEncodeStr(str)
	local result = ""
	for k,v in ipairs(string.ToTable(str)) do
		if k and v then
			if string.match(v,"[^%a]") then
				result = result .. "%" .. GetCharHex(v)
			else
				result = result .. v
			end
		end
	end
	return result
end

local function NetRequest(host,page,callback,post)
	local sock = OOSock(IPPROTO_TCP)
	local tab = {callback=callback}
	sock:SetCallback(function(self,typ,id,err,data,ip,port)
		--print(err,typ,data)
		if err ~= SCKERR_OK then
			self:Close()
			print("Closed socket on error " .. errcodes[err] .. "(ID: " .. tostring(id) .. ", TYP: " .. tostring(typ) .. ")")
		elseif typ == SCKCALL_CONNECT then
			--print("Connected")
			local postcont
			self:SendLine( (post and "POST" or "GET") .. " " .. page .. " HTTP/1.1")
			self:SendLine("Host: " .. host)
			if type(post) == "table" then
				postcont = ""
				local addamp = false
				for k,v in pairs(post) do
					if addamp then
						postcont = postcont .. "&"
					else
						addamp = true
					end
					postcont = postcont .. tostring(k) .. "=" .. HexEncodeStr(tostring(v))
				end
				self:SendLine("Content-Type: application/x-www-form-urlencoded")
				self:SendLine("Content-Length: " .. tostring(string.len(postcont)))
			end
			self:SendLine("")
			if postcont then
				self:Send(postcont)
			end
			--print("Sent headers")
			self:ReceiveLine()
		elseif typ == SCKCALL_REC_LINE then
			if tab.linedata then
				if string.Trim(data) == "" then
					if tab.callback then tab.callback(tab.linedata) end
				else
					tab.linedata = tab.linedata .. data .. "\n"
					self:ReceiveLine()
				end
			else
				if string.Trim(data) == "" then
					if tab.len then
						--print("Length was " .. tostring(tab.len))
						self:Receive(tab.len)
					else
						--print("No length!")
						tab.linedata = ""
						self:ReceiveLine()
					end
				else
					local len = string.match(data, "Content%-Length: (.*)")
					if len then tab.len = tonumber(len) end
					self:ReceiveLine()
				end
			end
		elseif typ == SCKCALL_REC_SIZE then
			if tab.callback then tab.callback(data) end
			self:Close()
		end
	end)
	sock:Connect(host,80)
	return sock
end

local function NetRequestAutoFormat(address,callback,post)
	local host,target = string.match(address,"http://([^/]*)(.*)")
	if not (host and target) then
		error("Invalid address: " .. tostring(address))
	end
	
	return NetRequest(host,target,callback,post)
end

local function OmegleStrToTable(str)
	local tab = string.ToTable(str)
	local tabend = #tab
	local inelement = false
	local returntab = {}
	local strings,curstring
	for k,v in ipairs(tab) do
		if k ~= 1 and k ~= tabend then
			if curstring then
				if v == '"' and tab[k-1] ~= "\\" then
					table.insert(strings, curstring)
					curstring = nil
				else
					curstring = curstring .. v
				end
			else
				if v == "[" then
					inelement = true
					strings = {}
				elseif v == "]" then
					inelement = false
					table.insert(returntab,strings)
				elseif v == '"' then
					curstring = ""
				end
			end
		end
	end
	return returntab
end

local evsock,sendsock

local omegleid,GetEvents,active
local queuedchat = {}

timer.Create("OmegleChat",(LocalPlayer():IsAdmin() and 1.2345 or 2.5),0,function()
	local msg = queuedchat[1]
	if msg then
		table.remove(queuedchat,1)
		RunConsoleCommand("say", msg)
	end
end)

local maxmsglen = 127
local function ChatQueue(str,sender)
	str = tostring(str)
	sender = sender or "Omegle: "
	local sendlen = maxmsglen-string.len(sender)
	while(string.len(str) ~= 0) do
		table.insert(queuedchat,sender .. string.sub(str,1,sendlen))
		str = string.sub(str, sendlen+1)
	end
end

local function ChatQueueStranger(str)
	ChatQueue(tostring(str), "Stranger: ")
end

local function SendMessage(str, ply)
	if not (omegleid and active) then return end
	print(str,ply)
	-- sendsock = NetRequestAutoFormat("http://promenade.omegle.com/send", function(s) print("Win?",s) end, {id=omegleid,msg=((ply and (ply:Nick() .. " :") or "") .. str)})
	sendsock = NetRequestAutoFormat("http://promenade.omegle.com/send", function(s) print("Win?",s) end, {id=omegleid,msg=str})
end

hook.Add("FinishChat","OmegleReset",function() timer.Start("OmegleChat") print("Reset counter") end)

local function OnPlayerChat(p,t)
	local ok = true
	if p == LocalPlayer() then
		timer.Start("OmegleChat")
		if string.match(t,"^%a*: .*$") then print("Supressing message...") ok = false end
	end
	
	if ok and omegleid and active and ValidEntity(p) and p:IsPlayer() then
		SendMessage(t,p)
	end
end

-- NoXiousNet NDB compatibility hack
if NDB and NDB.FullChatText then
	if not NOXIOUSNETCHATHOOK then
		NOXIOUSNETCHATHOOK = NDB.FullChatText
	end
	function NDB.FullChatText(entid, name, text, filter, teamonly, channel)
		local ent = Entity(entid)
		if ValidEntity(ent) and ent:IsPlayer() then
			OnPlayerChat(ent,text)
		end
		
		return NOXIOUSNETCHATHOOK(entid, name, text, filter, teamonly, channel)
	end
end

hook.Add("OnPlayerChat", "Omegle", OnPlayerChat)

-- connected, typing, gotMessage(str), strangerDisconnected
-- /start, /typing(id), /send(id,msg), /events(id), /disconnect(id)

local function CallbackEvents(str)
	print("CallbackEvents", str)
	if str == "null" then
		print("Ending EventChain")
		--omegleid = nil
		return
	end
	
	if not string.match(str,"%[.*%]") then return end
	local tab = OmegleStrToTable(str)
	
	for k,v in ipairs(tab) do
		local command = v[1]
		table.remove(v,1)
		
		if command == "connected" then
			ChatQueue("Connected to a new person!")
		elseif command == "count" then
		elseif command == "typing" then
		elseif command == "waiting" then
			ChatQueue("Waiting for a new stranger...")
		elseif command == "gotMessage" then
			ChatQueueStranger(v[1] or "~NULL~")
		elseif command == "strangerDisconnected" then
			ChatQueue("The other party disconnected :(")
			active = nil
			--omegleid = nil
		else
			ChatQueue("Unhandled event " .. command)
		end
	end
	
	GetEvents()
end

GetEvents = function()
	if not omegleid then error("Trying to call GetEvents without omegleid") end
	--print("Sending getevent for id " .. omegleid)
	--if evsock then evsock:Close() end
	evsock = NetRequestAutoFormat("http://promenade.omegle.com/events",CallbackEvents,{id=omegleid})
end

local function CallbackNew(str)
	omegleid = string.match(str,'"(.*)"')
	if omegleid then
		active = true
		print("Connected to " .. omegleid)
		GetEvents()
	end
end

concommand.Add("omegle_new", function()
	NetRequestAutoFormat("http://promenade.omegle.com/start",CallbackNew)
end)

concommand.Add("omegle_stop", function()
	queuedchat = {}
	active = false
	NetRequestAutoFormat("http://promenade.omegle.com/disconnect",nil,{id=omegleid})
end)
