/*
* 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 "test-offer-dbustube.h"
#include "example.h"
#include <KTelepathy/OfferDBusTubeJob>
#include <KTelepathy/TelepathyBridge>

#include "ontologies/nco.h"
#include "ontologies/informationelement.h"
#include "ontologies/person.h"
#include "ontologies/imaccount.h"

extern "C"
{
#include <signal.h>
}

#include <QTimer>
#include <QDBusConnection>
#include <QTcpSocket>

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

#include <Nepomuk/ResourceManager>
#include <Nepomuk/Resource>
#include <Nepomuk/Variant>
#include <Nepomuk/Query/QueryServiceClient>
#include <Nepomuk/Query/ComparisonTerm>
#include <Nepomuk/Query/ResourceTerm>
#include <Nepomuk/Query/ResourceTypeTerm>
#include <Nepomuk/Query/LiteralTerm>
#include <Nepomuk/Query/AndTerm>
#include <Nepomuk/Query/Result>




namespace
{
    static void signal_handler(int signal)
    {
        if ((signal == SIGTERM) || (signal == SIGINT)) {
            QCoreApplication * const app(QCoreApplication::instance());
            if (app != 0) {
                kDebug() << "Signal Handler Called. Exiting...";
                app->quit();
            }
        }
    }
}


int main(int argc, char** argv)
{
    KAboutData aboutData("telepathy_test_offer_dbustube", 0, ki18n("Test OfferDBusTube"), "0.1");

    KCmdLineArgs::init(argc, argv, &aboutData);
    KApplication app;

    Nepomuk::ResourceManager::instance()->init();

    // Set up signal handlers.
    if (signal(SIGINT, signal_handler) == SIG_ERR) {
        kWarning() << "Setting up SIGINT signal handler failed.";
    }

    if (signal(SIGTERM, signal_handler) == SIG_ERR) {
        kWarning() << "Setting up SIGTERM signal handler failed.";
    }

    Test::OfferDBusTube* window = new Test::OfferDBusTube(0);
    window->show();

    // Start event loop.
    return app.exec();
}



namespace Test {

OfferDBusTube::OfferDBusTube(QWidget* parent)
    : QDialog(parent),
      m_dbusConnection(QLatin1String("none"))
{
    kDebug();

    // Check if Nepomuk Query service client is up and running
    if (!Nepomuk::Query::QueryServiceClient::serviceAvailable()) {
        // That's a failure
        KMessageBox::error(this, i18n("The Nepomuk Query Service client is not available on your system. "
                                      "Contactlist requires the query service client to be available: please "
                                      "check your system settings"));
    }

    setupUi(this);

    // Initialize Telepathy
    KTelepathy::TelepathyBridge::instance()->init();
//    connect(TelepathyBridge::instance(),
//            SIGNAL(ready(bool)),
//            SLOT(onHandlerReady(bool)));

    // Get 'me' as soon as possible
    // FIXME: Port to new OSCAF standard for accessing "me" as soon as it
    // becomes available.
    Nepomuk::Thing me(QUrl::fromEncoded("nepomuk:/myself"));


    // Loop through all the grounding instances of this person
    foreach (Nepomuk::InformationElement resource, me.groundingOccurrences()) {
        // See if this grounding instance is of type nco:contact.
        if (resource.hasType(Nepomuk::Vocabulary::NCO::PersonContact())) {
            // FIXME: We are going to assume the first NCO::PersonContact is the
            // right one. Can we improve this?
            m_mePersonContact = resource;
            break;
        }
    }

    connect(m_runPushButton, SIGNAL(clicked()),
            this,            SLOT(onRunPushButtonClicked()));

    connect(m_modeComboBox, SIGNAL(currentIndexChanged(int)),
            this,           SLOT(onModeChanged(int)));

    m_example = new Example(this);
}


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


void OfferDBusTube::onModeChanged(int mode)
{
    switch (mode)
    {
        case 0:
            m_contactComboBox->setDisplayMode(KTelepathyAccountsWidget::DisplayModeContacts);
            break;
        case 1:
            m_contactComboBox->setDisplayMode(KTelepathyAccountsWidget::DisplayModeMetaContacts);
            break;
        default:
            break;
    }
}


void OfferDBusTube::onRunPushButtonClicked()
{
    kDebug();

    int mode = m_modeComboBox->currentIndex();
    KJob* job;

    switch (mode)
    {
        case 0:
        {
            Nepomuk::PersonContact targetContact = m_contactComboBox->currentContact();
            job = KTelepathy::TelepathyBridge::instance()->offerDBusTube(targetContact, "org.freedesktop.Telepathy.Qt4.Example");
            break;
        }
        case 2:
        {
            Nepomuk::Person targetMetaContact = m_contactComboBox->currentMetaContact();
            job = KTelepathy::TelepathyBridge::instance()->offerDBusTube(targetMetaContact, "org.freedesktop.Telepathy.Qt4.Example");
            break;
        }
        default:
            break;
    }

    if (job) {
        connect (job,  SIGNAL(infoMessage(KJob*,QString,QString)),
                 this, SLOT(onInfoMessage(KJob*,QString,QString)));
    }

    if (m_runComboBox->currentIndex() == 0)
        asyncCall(job);
    else
        syncCall(job);
}


void OfferDBusTube::asyncCall(KJob* job)
{
    connect( job,  SIGNAL(result(KJob*)),
             this, SLOT  (handleResult(KJob*)));
    job->start();
}


void OfferDBusTube::handleResult(KJob * job)
{
    if ( job->error() ) {
        // TODO do something;
    }

    KTelepathy::OfferDBusTubeJob* offerDBusTubeJob = dynamic_cast<KTelepathy::OfferDBusTubeJob*>(job);
    if(!offerDBusTubeJob) {
        // Not an OfferDBusTubeJob
        return;
    }
    kDebug() << m_dbusConnection.name();
    m_dbusConnection = offerDBusTubeJob->dbusConnection();
    kDebug() << m_dbusConnection.name();
    registerExample();
}


void OfferDBusTube::syncCall(KJob* job)
{
    if ( !job->exec() ) {
        // An error occurred
    } else {
        KTelepathy::OfferDBusTubeJob* offerDBusTubeJob = dynamic_cast<KTelepathy::OfferDBusTubeJob*>(job);
        if(!offerDBusTubeJob) {
            // Not an OfferDBusTubeJob
            return;
        }
        kDebug() << m_dbusConnection.name();
        m_dbusConnection = offerDBusTubeJob->dbusConnection();
        kDebug() << m_dbusConnection.name();
        registerExample();
    }
}


bool OfferDBusTube::registerExample()
{
    bool ret = m_dbusConnection.registerObject(QLatin1String("/"), m_example);

    if (!ret) {
        kDebug() << i18n("m_dbusConnection.registerObject: FAIL");
        return false;
    }
    else
        kDebug() << i18n("m_dbusConnection.RegisteredObject: SUCCESS");
    if (m_dbusConnection.objectRegisteredAt(QLatin1String("/")) != m_example) {
        kDebug() << i18n("m_dbusConnection.objectRegisteredAt: FAIL");
        return false;
    }
    else
        kDebug() << i18n("m_dbusConnection.objectRegisteredAt: SUCCESS");
    return true;
}


void OfferDBusTube::onInfoMessage(KJob* job, const QString &plain, const QString &rich)
{
    Q_UNUSED(job)
    kDebug() << plain;

    KNotification::event("newOfferDBusTubeEvent", plain, rich);
}

} // end namespace Test
