/*
* Copyright (C) 2010 Daniele E. Domenichelli <daniele.domenichelli@gmail.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "p2pdbustube-handler.h"
#include "example.h"
#include "exampleinterface.h"

#include <KTelepathy/HandleP2PDBusTubeJob>

#include <QDBusConnection>

#include <KAboutData>
#include <KCmdLineArgs>
#include <KDebug>
#include <KApplication>
#include <KNotification>

#include <TelepathyQt4/Channel>
#include <TelepathyQt4/Account>


#define P2PDBUS_SERVICENAME "org.kde.KTelepathy.Test.P2PDBus"

namespace Test {


P2PDBusTubeHandler::P2PDBusTubeHandler(QObject* parent)
    : QObject(parent),
      Tp::AbstractClientHandler(KTelepathy::P2PDBusTubeClientHandlerChannelClassList(P2PDBUS_SERVICENAME), false)
{
    kDebug();
}


P2PDBusTubeHandler::~P2PDBusTubeHandler()
{
    kDebug();
}

bool P2PDBusTubeHandler::bypassApproval() const
{
    kDebug() << "bypassing";
    return false;
}

void P2PDBusTubeHandler::handleChannels(const Tp::MethodInvocationContextPtr<> & context,
        const Tp::AccountPtr & account,
        const Tp::ConnectionPtr & connection,
        const QList<Tp::ChannelPtr> & channels,
        const QList<Tp::ChannelRequestPtr> & requestsSatisfied,
        const QDateTime & userActionTime,
        const QVariantMap & handlerInfo)
{
    Q_UNUSED(account);
    Q_UNUSED(connection);
    Q_UNUSED(requestsSatisfied);
    Q_UNUSED(userActionTime);
    Q_UNUSED(handlerInfo);

    foreach(const Tp::ChannelPtr &channel, channels) {
        kDebug() << "Handling channel" << channel;
        QVariantMap properties = channel->immutableProperties();
        kWarning() << "channel properties:" << properties;

        if (properties[TELEPATHY_INTERFACE_CHANNEL ".ChannelType"] == TELEPATHY_INTERFACE_CHANNEL_TYPE_DBUS_TUBE &&
            properties[TELEPATHY_INTERFACE_CHANNEL_TYPE_DBUS_TUBE ".ServiceName"] == P2PDBUS_SERVICENAME)
        {
            kWarning() << "Handling:" << TELEPATHY_INTERFACE_CHANNEL_TYPE_DBUS_TUBE << P2PDBUS_SERVICENAME;

            KJob* job = handleP2PDBusTube(channel, QVariantMap(), false, KTelepathy::HandleChannelAny, this);

            if (job) {
                kWarning() << "Job created";
                connect (job, SIGNAL(infoMessage(KJob*,QString,QString)),
                         this, SLOT(onInfoMessage(KJob*,QString,QString)));
                connect (job, SIGNAL(result(KJob*)),
                         this, SLOT(onHandleP2PDBusTubeJobResult(KJob*)));
                kWarning() << "Starting job";
                job->start();
            } else {
                kWarning() << "Cannot create job";
            }
        }
    }
    context->setFinished();
}


void P2PDBusTubeHandler::onHandleP2PDBusTubeJobResult(KJob* job)
{
    kWarning();
    if ( job->error() ) {
        kWarning() << "Job error!" << job->error() << job->errorString();
        // TODO do something;
    }

    KTelepathy::HandleP2PDBusTubeJob* handleP2PDBusTubeJob = dynamic_cast<KTelepathy::HandleP2PDBusTubeJob*>(job);
    if(!handleP2PDBusTubeJob) {
        kWarning() << "Job is not a HandleP2PDBusTubeJob";
        // Not an AcceptDBusTubeJob
        return;
    }

    Test::ExampleDialog* dialog = new Test::ExampleDialog(0);
    kDebug() << handleP2PDBusTubeJob->dbusConnection().name();
    dialog->m_dbusConnection = handleP2PDBusTubeJob->dbusConnection();
    dialog->registerExample();
    dialog->useExample();
    dialog->show();

    //    dialog->m_contactLineEdit->setText(properties[TELEPATHY_INTERFACE_CHANNEL ".InitiatorID"].toString());


//    m_incomingDBusTubeChannel = acceptDBusTubeJob->incomingDBusTubeChannel();
//    m_dbusConnection = acceptDBusTubeJob->dbusConnection();
}

void P2PDBusTubeHandler::onInfoMessage(KJob* job, const QString &plain, const QString &rich)
{
    Q_UNUSED(job)
    kWarning() << plain;
    KNotification::event("newDBusTubeHandlerEvent", plain, rich);
}


} // end namespace Test
