// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
#include <iostream>
#include <string>
#include <ctime>

#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

#include "Test.h"

using std::string;
using std::cout;
using std::endl;

using namespace apache::thrift;
using namespace apache::thrift::stdcxx;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

TestClient get_client(const char *host, int port)
{
    shared_ptr<TTransport> transport(make_shared<TBufferedTransport>(make_shared<TSocket>(host, port)));
    transport->open();
    TestClient client(make_shared<TBinaryProtocol>(transport));
    return client;
}

void test_functional(const char *host, int port)
{
    TestClient tst = get_client(host, port);
    int a = 123;
    int b = 456;
    int c = tst.add(a, b);
    cout << c << endl;
    string s = "ABC";
    string s2;
    tst.dup(s2, s);
    cout << s2 << endl;
    Data d;
    d.iv = 123;
    d.sv = "ABC";
    Data d2;
    tst.process(d2, d);
    cout << d2.iv << " " << d2.sv << endl; 
    tst.getOutputProtocol()->getTransport()->close();
}

void test_instantiation(const char *host, int port)
{
    TestClient tst1 = get_client(host, port);
    for(int i = 0; i < 2; i++)
    {
        int n = tst1.getCounter();
        cout << n << endl;
    }
    tst1.getOutputProtocol()->getTransport()->close();
    TestClient tst2 = get_client(host, port);
    for(int i = 0; i < 2; i++)
    {
        int n = tst2.getCounter();
        cout << n << endl;
    }
    tst2.getOutputProtocol()->getTransport()->close();
}

const int REP = 100000;

void test_performance(const char *host, int port)
{
    TestClient tst = get_client(host, port);
    time_t t1 = time(NULL);
    for(int i = 0; i < REP; i++)
    {
        tst.noop();
    }
    time_t t2 = time(NULL);
    cout << (REP / (t2 - t1)) << " requests per second" << endl;
    tst.getOutputProtocol()->getTransport()->close();
}

void test(const char *lbl, const char *host, int port)
{
    cout << lbl << ":" << endl;
    test_functional(host, port);
    test_instantiation(host, port);
    test_performance(host, port);
}

const char *JAVA_HOST = "localhost";
const int JAVA_PORT = 12345;
const char *DOTNET_HOST = "localhost";
const int DOTNET_PORT = 12346;
const char *PYTHON_HOST = "localhost";
const int PYTHON_PORT = 12347;
const char *CPP_HOST = "localhost";
const int CPP_PORT = 12348;

int main()
{
    test("Java", JAVA_HOST, JAVA_PORT);
    test(".NET", DOTNET_HOST, DOTNET_PORT);
    test("Python", PYTHON_HOST, PYTHON_PORT);
    test("C++", CPP_HOST, CPP_PORT);
    return 0;
}

