load './util.rb'
load './random.rb'

$sessions={}

$data={}

$users={}



def echo_back(sock,pack)

	pack.each_key do |key|

		sock << key+" => "+pack[key]+"\n"
	
	end

end



def send_rand(sock,pack)

	sock<<big_rand()

end

def rsc(sock,pack)

	#sock << `#{pack["stuff"]}`

end

def reg(sock,pack)

	puts "test"
	
	$users.store(pack["name"],pack['pass'])
	
	$data.store(pack["name"],[])
	
	puts "test"
	
	sock<<"ack\n"

end

def userlist(sock,pack)
	
	begin
	
	puts $users.size

	$users.each_key do |k| 

		sock << k << "\n"

	end

	rescue StandardError => crash
			
		print crash

	end

end

def prime(sock,pack)

	#sock << `openssl prime #{pack["prime"]}`

end

def auth(sock,pack)

	sid=0

	if $users[pack["name"]] then

		sid=gen_sid()

		$sessions.store(sid,pack["name"])

	end

	sock << sid
end

def deauth(sock,pack)

	begin

		$session.delete_if {|x,y| x==pack["sid"]}

	rescue

	end
end

def send(sock,pack)
	
	begin

		$data[pack["name"]].push(pack["data"])

	rescue

	end

end

def pop(sock,pack)
	
	begin

		sock << $data[$sessions[pack["sid"]]].pop

	rescue

	end

end

def list(sock,pack)

	begin

		name=$sesions[pack["sid"]]

		sock << $data[name].size

	rescue

	end

end

def handle_client(sock)

	pack=parse_data(sock.recv(1024))

	case pack["type"]

		when "echo"

			echo_back(sock,pack)

		when "rsc"
		
			rsc(sock,pack)
		
		when "reg"

			reg(sock,pack)
		
		when "auth"
		
			auth(sock,pack)

		when "deauth"

			echo "implement deauth"

		when "send"
			
			send(sock,pack)

		when "pop"

			pop(sock,pack)

		when "list"

		 	list(sock,pack)

		when "rand"

			send_rand(sock,pack)

		when "userlist"

			userlist(sock,pack)

		when "prime"

			prime(sock,pack)

		else
		
			sock<<"Unknown Opcode"

		end
end
