#include "ListChannelsRequest.hpp"
#include "../../include/XmlRpc.h"
#include "../../responses/ListChannelsResponse.hpp"
#include "../../XmlRpcppClient.hpp"
#include <iostream>

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

xmlrpcpp::ListChannelsRequest::ListChannelsRequest(){}

xmlrpcpp::ListChannelsRequest::~ListChannelsRequest(){}

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

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

    XmlRpcValue args, result;
    /* args = Client identificator */
    args = c->getId();
    if (rpcClient->execute(name().c_str(), args, result)){
	serv::ListChannelsResponse * resp = new serv::ListChannelsResponse();
	if (result.hasMember("faultCode")){
	    resp->error(result["faultCode"], result["faultString"]);
	}
	else {
	    // The response contains the list of all chans
	    for (int i = 0; i < result.size(); i++){
		resp->addChannel(result[i]);
	    }
	}
	return resp;
    }
    return NULL;
}
