/*
 * QtTapioca, the Tapioca Qt4 Client Library
 * Copyright (C) 2006 by INdT
 *  @author Andre Moreira Magalhaes <andre.magalhaes@indt.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <QtCore/QtCore>
#include <QtCore/QString>
#include <QtTapioca/ConnectionManager>
#include <QtTapioca/ConnectionManagerFactory>
#include <QtTapioca/Connection>
#include <QtTapioca/Contact>
#include <QtTapioca/ContactBase>
#include <QtTapioca/ContactList>
#include <QtTapioca/TextChannel>

#include "test.h"

using namespace QtTapioca;

static Connection *conn = NULL;
int main(int argc, char **argv)
{
    if (argc < 3) {
        qDebug() << "usage: test username@gmail.com password";
        qDebug() << "       test username@host password server port";
        return 1;
    }

    // create the QApplication object
    QCoreApplication app(argc, argv);

    ConnectionManagerFactory *factory = ConnectionManagerFactory::self();
    QList<ConnectionManager*> cms = factory->getAllConnectionManagers();
    ConnectionManager *cm;
    QList<Connection *> connList;
    ConnectionManager::Parameter param;
    foreach (cm, cms) {
        qDebug() << "ConnectionManager info:";
        qDebug() << "\tname:" << cm->name();

        QString protocol;
        QStringList protocols = cm->supportedProtocols();

        qDebug() << "\tsupported protocols:" << cm->supportedProtocols();

        foreach (protocol, protocols) {
            QList<ConnectionManager::Parameter> params = cm->protocolParameters(protocol);
            foreach (param, params)
                qDebug() << "\t\tparams name:" << param.name() << "value:" << param.value() << "flags:" << param.flags();
        }

        qDebug() << "\tis running:" << cm->isRunning();
        connList = cm->connections();
        if (connList.empty())
            continue;
        qDebug() << "\tconnections:";
        foreach (conn, connList) {
            qDebug() << "\t\t" << conn->serviceName() << ":" << conn->objectPath();
        }
    }
    cm = factory->getConnectionManager("jabber");
    if (!cm) {
        return 1;
    }

    /* fill params */
    QList<ConnectionManager::Parameter> params;
    params.append(ConnectionManager::Parameter("account", QVariant(argv[1])));
    params.append(ConnectionManager::Parameter("password", QVariant(argv[2])));
    QString account(argv[1]);
    if (account.endsWith("@gmail.com") || account.endsWith("@googlemail.com")) {
        params.append(ConnectionManager::Parameter("server", QVariant("talk.google.com")));
        params.append(ConnectionManager::Parameter("old-ssl", QVariant(true)));
        params.append(ConnectionManager::Parameter("ignore-ssl-errors", QVariant(true)));
        params.append(ConnectionManager::Parameter("port", QVariant((uint) 5223)));
    }
    else {
        if (argc < 5) {
            qDebug() << "usage: test username@host password server port";
            return 1;
        }
        params.append(ConnectionManager::Parameter("server", QVariant(argv[3])));
        params.append(ConnectionManager::Parameter("port", QVariant(QString(argv[4]).toUInt())));
    }
    conn = cm->requestConnection("jabber", params);
    if (!conn) {
        return 1;
    }
    MessageFilter messageFilter;
    QObject::connect(conn, SIGNAL(statusChanged(QtTapioca::Connection *, QtTapioca::Connection::Status, QtTapioca::Connection::Reason)),
                     &messageFilter, SLOT(onStatusChanged(QtTapioca::Connection *, QtTapioca::Connection::Status, QtTapioca::Connection::Reason)));
    QObject::connect(conn, SIGNAL(channelCreated(QtTapioca::Connection *, QtTapioca::Channel *, bool)),
                     &messageFilter, SLOT(onChannelCreated(QtTapioca::Connection *, QtTapioca::Channel *, bool)));
    conn->connect(ContactBase::Available);

    return app.exec();
}

MessageFilter::MessageFilter(QObject *parent)
    : QObject(parent)
{
}

MessageFilter::~MessageFilter()
{
}

void MessageFilter::onStatusChanged(Connection *connection, Connection::Status status, Connection::Reason reason)
{
    qDebug() << "Connection status changed to" << status << "- reason" << reason;
    if (status == Connection::Connected) {
        ContactList *cl = conn->contactList();
        Contact *contact = NULL;
        QList<Contact *> allContact = cl->knownContacts();

        qDebug() << "\nretrieving contact list ...";
        foreach (contact, allContact) {
            qDebug() << "\turi:" << contact->uri() << "status:" << contact->subscriptionStatus();
        }
    }
}

void MessageFilter::onChannelCreated(Connection *connection, Channel *channel, bool suppress)
{
    if (channel->type() == Channel::Text) {
        TextChannel *tch =  dynamic_cast<TextChannel*>(channel);

        QList<TextChannel::Message> msgList = tch->pendingMessages();
        foreach (TextChannel::Message m, msgList) {
            qDebug() << m.contents();
            tch->acknowledge(m);
        }

        QObject::connect(tch, SIGNAL(messageReceived(const QtTapioca::TextChannel *,
                                                     const QtTapioca::TextChannel::Message &)),
                         this,
                         SLOT(onMessageReceived(const QtTapioca::TextChannel *, const QtTapioca::TextChannel::Message &)));
    }
}

void MessageFilter::onMessageReceived(const TextChannel *tch, const TextChannel::Message &msg)
{
    TextChannel *t =  const_cast<TextChannel*>(tch);

    qDebug() << msg.contents();

    t->sendMessage("reply");
    t->acknowledge(msg);
}
