#include "Client.hpp"
#include "Request.hpp"

using namespace mole;
using namespace ctx;

Client::Client(Server * s):server(s), requestFactory(new RequestFactory()){}

Client::Client():server(new Server()),requestFactory(new RequestFactory()){}

Client::~Client(){
    delete server;
    delete requestFactory;
}

Server *
Client::getServer(){
    return server;
}

bool
Client::bind(Server * s, bool co){
    if (this->server)
	delete server;

    this->server = s;
    /* Trying connection only if co is true */
    return co && connect();
}

mole::serv::Service *
Client::getService(std::string name){
    mole::serv::Service * s = server->getService(name);
    if (s != NULL){
	mole::ctx::Request * r = createRequest(name);
	if (r != NULL){
	    return s->newInvocableService(r);
	}
    }
    return NULL;
}

bool
Client::connect(){
    return true;
}

void
Client::disconnect(){}


bool
Client::execute(mole::serv::Service * service){
    return service->execute(this);
}

bool
Client::init(){
    return true;
}

mole::ctx::Request *
Client::createRequest(std::string name){
    mole::ctx::Request * req = requestFactory->getRequest(name)->newRequest();
    req->setName(name);
    return req;
}

void
Client::addRequest(std::string name, mole::ctx::Request * req){
    requestFactory->addRequest(name, req);
}
