/***************************************************************************
 *   Copyright (C) 2003 by Fred Schaettgen                                 *
 *   kdebluetooth@schaettgen.de                                            *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include "dcopcall.h"

DCOPCall::DCOPCall(DCOPClient* client, QString app, QString obj)
{
    this->client = client;
    this->app = app;
    this->obj = obj;
    this->argStream = new QDataStream(argArray, IO_WriteOnly);
    this->retStream = new QDataStream(retArray, IO_WriteOnly);
}

DCOPCall::~DCOPCall()
{
    if (argStream) delete this->argStream;
    if (retStream) delete this->retStream;
}

QString DCOPCall::call(QString func) {
    delete retStream;
    retArray = QByteArray();
    retStream = new QDataStream(retArray, IO_ReadOnly);

    QCString replyType;
    if (client->call(app.ascii(), obj.ascii(),
        func.ascii(), argArray, replyType, retArray))
    {
        delete argStream;
        argArray = QByteArray();
        argStream = new QDataStream(argArray, IO_WriteOnly);

        return replyType;
    }
    else {
        return QString::null;
    }
}

// A.I., 2004-Jan-16
QStringList DCOPCall::broadcast(QString func, bool includeself, bool onlyfirst)
{
    QStringList ret;
    QString origApp = app;
    QString myAppId = QString(client->appId());
    QCStringList apps = client->registeredApplications();
    for (uint n=0; n<apps.count(); ++n) {
        QString listedApp = apps[n];
        if (listedApp.startsWith(origApp) && ((listedApp!=myAppId) || includeself)) {
            app = listedApp;
            ret.append( call(func) );
            if(onlyfirst) break;
        }
    }
    app = origApp;
    return ret;
}

QDataStream& DCOPCall::args() {
    return *argStream;
}

QDataStream& DCOPCall::ret() {
    return *retStream;
}


