

import threading
import time
import uuid

import escp.messaging.coders as coders
import escp.messaging.rpc as rpc
import escp.messaging.session as session
import escp.tools.reactor as reactor
import escp.tools.records as records


_instance_count = 8
_call_count = 64


def _server_handler (_request) :
	if _request[0] == 'ping' :
		_response = ('pong', _request[1])
	else :
		_response = 'what?'
	return _response


def _client (_context) :
	
	_server_agent = uuid.uuid4 () .hex
	_server_port = uuid.uuid4 () .hex
	
	_session = session.Session (_context.reactor, '127.0.0.1:27683', 'guest', 'guest', False)
	_coder = coders.JsonCoder ()
	_client = rpc.Client (_session, None, None, _coder)
	_server = rpc.PortServer (_session, _server_agent, _server_port, _coder, _server_handler)
	
	_session.open_sync ()
	_client.initialize_sync ()
	_server.initialize_sync ()
	
	_start = time.time ()
	
	for _index in xrange (_call_count) :
		_token = uuid.uuid4 () .hex
		_request = ('ping', _token)
		_response = _client.call_port_sync (_server_agent, _server_port, _request)
		assert _response[0] == 'pong' and _response[1] == _token
	
	_stop = time.time ()
	_elapsed = _stop - _start
	_average = _elapsed / _call_count
	print _elapsed, _call_count, _average
	
	_server.finalize_sync ()
	_client.finalize_sync ()
	_session.close_sync ()
	
	_context.done += 1
	
	return


def test () :
	_threaded = True
	_reactor = reactor.Reactor (threaded = _threaded, lock = threading.RLock ())
	_reactor.start ()
	_context = records.Record (reactor = _reactor, done = 0)
	for _index in xrange (_instance_count) :
		threading.Thread (target = lambda : _client (_context)) .start ()
	while _context.done != _instance_count :
		if _threaded :
			time.sleep (0.1)
		else :
			_reactor.iterate ()
	_reactor.stop ()
	return


if __name__ == '__main__' :
	test ()
