# 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

import google
import grpc

import test_pb2
import test_pb2_grpc

def testFunctional(host, port):
    ch = grpc.insecure_channel(host + ':' + str(port))
    tst = test_pb2_grpc.TestStub(ch)
    a = 123
    b = 456
    c = tst.Add(test_pb2.AddRequest(a = a, b = b)).c
    print(str(c))
    s = 'ABC'
    s2 = tst.Dup(test_pb2.DupRequest(s = s)).s2
    print(s2)
    d = test_pb2.Data(iv = 123, sv = 'ABC')
    d2 = tst.Process(d)
    print('%d %s' % (d2.iv, d2.sv))
    ch.close()

def testInstantiation(host, port):
    ch1 = grpc.insecure_channel(host + ':' + str(port))
    tst1 = test_pb2_grpc.TestStub(ch1)
    for i in range(0, 2):
        n = tst1.GetCounter(google.protobuf.empty_pb2.Empty()).counter
        print(str(n))
    ch1.close()
    ch2 = grpc.insecure_channel(host + ':' + str(port))
    tst2 = test_pb2_grpc.TestStub(ch2)
    for i in range(0, 2):
        n = tst2.GetCounter(google.protobuf.empty_pb2.Empty()).counter
        print(str(n))
    ch2.close()

REP = 10000

def testPerformance(host, port):
    ch = grpc.insecure_channel(host + ':' + str(port))
    tst = test_pb2_grpc.TestStub(ch)
    t1 = time.time()
    for i in range(0, REP):
        tst.Noop(google.protobuf.empty_pb2.Empty())
    t2 = time.time()
    print('%d requests per second' % (REP / (t2 - t1)))
    ch.close()

def testStream(host, port):
    ch = grpc.insecure_channel(host + ':' + str(port))
    tst = test_pb2_grpc.TestStub(ch)
    for d2 in tst.StreamProcess(test_pb2.Data(iv = i, sv = chr(65 + i)) for i in range(0, 10)):
        print('%d %s' % (d2.iv, d2.sv))
    ch.close()

def testStreamPerformance(host, port):
    ch = grpc.insecure_channel(host + ':' + str(port))
    tst = test_pb2_grpc.TestStub(ch)
    t1 = time.time()
    for emp in tst.StreamNoop(google.protobuf.empty_pb2.Empty() for i in range(0, REP)):
        pass
    t2 = time.time()
    print('%d requests per second' % (REP / (t2 - t1)))
    ch.close()

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

test('Java', 'localhost', 12345)
test('.NET', 'localhost', 12346)
test('.NET (MS)', 'localhost', 12347)
test('Python', 'localhost', 12348)
test('C++', 'localhost', 12349)
