#include "ConnectionRequest.hpp"
#include "../../include/XmlRpc.h"
#include "../../responses/ConnectionResponse.hpp"
#include "../../XmlRpcppClient.hpp"
#include <iostream>

using namespace mole;
using namespace ctx;
using namespace xmlrpcpp;
using namespace XmlRpc;

xmlrpcpp::ConnectionRequest::ConnectionRequest(){}

xmlrpcpp::ConnectionRequest::~ConnectionRequest(){}

xmlrpcpp::ConnectionRequest *
xmlrpcpp::ConnectionRequest::newRequest(){
    return new xmlrpcpp::ConnectionRequest();
}

mole::serv::Response *
xmlrpcpp::ConnectionRequest::execute(Client * c){
    XmlRpcppClient * client = static_cast <XmlRpcppClient *> (c);
    XmlRpcClient * rpcClient = client->getRealClient();

    XmlRpcValue args, result;
    args.setSize(3);
    args[0] = login;
    args[1] = ip;
    args[2] = port;

    if (rpcClient->execute("mole.connection", args, result)){
	serv::ConnectionResponse * resp = new mole::serv::ConnectionResponse();
	if (!result.hasMember("faultCode")){
	    /* Result is the id given by server to auth the client.
	     * We save it into the client. */
	    resp->setLogin(login);
	    resp->setId(result);
	    client->setId(result);
	}
	else 
	    resp->error(result["faultCode"], result["faultString"]);
	return resp;
    }
    return NULL;
}
