#include "gtest/gtest.h"

#include "AbstractXreateServer.h"

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

#include <iostream>

using namespace std;

class RemoteConnection {
public:
    AbstractXreateServerClient* server;
    
    RemoteConnection(){
        __socket.reset(new apache::thrift::transport::TSocket("localhost", 9090));
        __transport.reset(new apache::thrift::transport::TBufferedTransport(__socket));
        __protocol.reset(new apache::thrift::protocol::TJSONProtocol(__transport));
        
         server = new AbstractXreateServerClient(__protocol);
         __transport->open();
    }
    
    ~RemoteConnection(){
        delete server;
        __transport->close();
    }
    
    
private:
    boost::shared_ptr<apache::thrift::transport::TTransport> __socket;
    boost::shared_ptr<apache::thrift::transport::TTransport> __transport;
    boost::shared_ptr<apache::thrift::protocol::TProtocol> __protocol;
};


TEST(Common, ping1){
    std::string responce;

    try {
        RemoteConnection connection;

        connection.server->ping(responce, "test1");
        std::cout << "ping: " << responce << std::endl;

    } catch (apache::thrift::TException& tx) {
        cout << "ERROR: " << tx.what() << endl;
    }
    
    ASSERT_STREQ("test1", responce.c_str());
}

TEST(Common, syntaxcheckSuccess1){
    SyntaxCheckResult r;
    
    try {
        RemoteConnection connection;
        
        const string program = 
            "a = function:: num; entry \
            {}";
                
        connection.server->checkSyntax(r, program);
        
        r.printTo(cout);cout << endl;
        
    } catch(apache::thrift::TException& tx){
        cout << "ERROR: " << tx.what() << endl;
    }
    
    ASSERT_TRUE(r.success);
}

TEST(Common, syntaxcheckFail1){
    SyntaxCheckResult r;
    
    try {
        RemoteConnection connection;
        
        const string program = 
            "a = function:: num; entry \
            {x+y.}";
                
        connection.server->checkSyntax(r, program);
        
        r.printTo(cout); cout << endl;
        
    } catch(apache::thrift::TException& tx){
        cout << "ERROR: " << tx.what() << endl;
    }
    
    ASSERT_TRUE(r.output.size() > 0);
    ASSERT_FALSE(r.success);
}

int main(int argc, char **argv) {
    testing::GTEST_FLAG(color) = "yes";
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}