# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import sys
import time

# get Thrift library
sys.path.append('C:\\DivJava\\thrift-0.11.0\\lib\\py\\build\\lib')
sys.path.append('C:\\DivJava\\thrift-0.11.0\\lib\\py\\build\\lib.win-amd64-2.7')
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

# get generated client stub
sys.path.insert(0, 'python')
from test import ttypes
from test import Test

def getClient(host, port):
    transport = TSocket.TSocket(host, port)
    transport.open()
    return Test.Client(TBinaryProtocol.TBinaryProtocol(TTransport.TBufferedTransport(transport)))

def testFunctional(host, port):
    client = getClient(host, port)
    a = 123
    b = 456
    c = client.add(a, b)
    print(str(c))
    s = 'ABC'
    s2 = client.dup(s)
    print(s2)
    d = ttypes.Data(123, 'ABC')
    d2 = client.process(d)
    print('%d %s' % (d2.iv, d2.sv))
    client._oprot.trans.close()

def testInstantiation(host, port):
    client1 = getClient(host, port)
    for i in range(0, 2):
        n = client1.getCounter()
        print(str(n))
    client1._oprot.trans.close()
    client2 = getClient(host, port)
    for i in range(0, 2):
        n = client2.getCounter()
        print(str(n))
    client2._oprot.trans.close()

def testPerformance(host, port):
    client = getClient(host, port)
    REP = 10000
    t1 = time.time()
    for i in range(0, REP):
        client.noop()
    t2 = time.time()
    print('%d requests per second' % (REP / (t2 - t1)))
    client._oprot.trans.close()

def test(lbl, host, port):
    print lbl + ':'
    testFunctional(host,port)
    testInstantiation(host, port)
    testPerformance(host, port)

test('Java', 'localhost', 12345)
test('.NET', 'localhost', 12346)
test('Python', 'localhost', 12347)

