/*
* 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-tcp-streamtube.h"
#include <KTelepathy/OfferTcpStreamTubeJob>
#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 <QTcpServer>
#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_tcp_streamtube", 0, ki18n("Test OfferTcpStreamTube"), "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::OfferTcpStreamTube* window = new Test::OfferTcpStreamTube(0);
    window->show();

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



namespace Test {

OfferTcpStreamTube::OfferTcpStreamTube(QWidget* parent)
    : QDialog(parent)
{
    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)));
}


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


void OfferTcpStreamTube::onModeChanged(int mode)
{
    switch (mode)
    {
        case 0:
            m_addressLineEdit->setEnabled(false);
            m_portIntSpinBox->setEnabled(false);
            m_contactComboBox->setDisplayMode(KTelepathyAccountsWidget::DisplayModeContacts);
            break;
        case 1:
            m_addressLineEdit->setEnabled(true);
            m_portIntSpinBox->setEnabled(true);
            m_contactComboBox->setDisplayMode(KTelepathyAccountsWidget::DisplayModeContacts);
            break;
        case 2:
            m_addressLineEdit->setEnabled(false);
            m_portIntSpinBox->setEnabled(false);
            m_contactComboBox->setDisplayMode(KTelepathyAccountsWidget::DisplayModeContacts);
            break;
        case 3:
            m_addressLineEdit->setEnabled(false);
            m_portIntSpinBox->setEnabled(false);
            m_contactComboBox->setDisplayMode(KTelepathyAccountsWidget::DisplayModeMetaContacts);
            break;
        case 4:
            m_addressLineEdit->setEnabled(true);
            m_portIntSpinBox->setEnabled(true);
            m_contactComboBox->setDisplayMode(KTelepathyAccountsWidget::DisplayModeMetaContacts);
            break;
        case 5:
            m_addressLineEdit->setEnabled(false);
            m_portIntSpinBox->setEnabled(false);
            m_contactComboBox->setDisplayMode(KTelepathyAccountsWidget::DisplayModeMetaContacts);
            break;
        default:
            break;
    }
}


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

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

    switch (mode)
    {
        case 0:
        {
            Nepomuk::PersonContact targetContact = m_contactComboBox->currentContact();
            job = KTelepathy::TelepathyBridge::instance()->offerTcpStreamTube(targetContact);
            m_server = dynamic_cast<KTelepathy::OfferTcpStreamTubeJob*>(job)->tcpServer();
            break;
        }
        case 1:
        {
            Nepomuk::PersonContact targetContact = m_contactComboBox->currentContact();
            job = KTelepathy::TelepathyBridge::instance()->offerTcpStreamTube(targetContact, QHostAddress(m_addressLineEdit->text()), m_portIntSpinBox->value());
            m_server = dynamic_cast<KTelepathy::OfferTcpStreamTubeJob*>(job)->tcpServer();
            break;
        }
        case 2:
        {
            Nepomuk::PersonContact targetContact = m_contactComboBox->currentContact();
            m_server = new QTcpServer;
            m_server->listen(QHostAddress::LocalHost, 20000);
            job = KTelepathy::TelepathyBridge::instance()->offerTcpStreamTube(targetContact, m_server);
            break;
        }
        case 3:
        {
            Nepomuk::Person targetMetaContact = m_contactComboBox->currentMetaContact();
            job = KTelepathy::TelepathyBridge::instance()->offerTcpStreamTube(targetMetaContact);
            m_server = dynamic_cast<KTelepathy::OfferTcpStreamTubeJob*>(job)->tcpServer();
            break;
        }
        case 4:
        {
            Nepomuk::Person targetMetaContact = m_contactComboBox->currentMetaContact();
            job = KTelepathy::TelepathyBridge::instance()->offerTcpStreamTube(targetMetaContact, QHostAddress(m_addressLineEdit->text()), m_portIntSpinBox->value());
            m_server = dynamic_cast<KTelepathy::OfferTcpStreamTubeJob*>(job)->tcpServer();
            break;
        }
        case 5:
        {
            Nepomuk::Person targetMetaContact = m_contactComboBox->currentMetaContact();
            m_server = new QTcpServer;
            m_server->listen(QHostAddress::LocalHost, 20000);
            job = KTelepathy::TelepathyBridge::instance()->offerTcpStreamTube(targetMetaContact, m_server);
            break;
        }
        default:
            break;
    }

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

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


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


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

//     OfferTcpStreamTubeJob* offerTcpStreamTubeJob = dynamic_cast<OfferTcpStreamTubeJob*>(job);
//     if(!offerTcpStreamTubeJob) {
//         // Not an OfferTcpStreamTubeJob
//         return;
//     }
//     m_outgoingStreamTubeChannel = offerTcpStreamTubeJob->outgoingStreamTubeChannel();
}


void OfferTcpStreamTube::syncCall(KJob* job)
{
    if ( !job->exec() ) {
        // An error occurred
    } else {
//         OfferTcpStreamTubeJob* offerTcpStreamTubeJob = dynamic_cast<OfferTcpStreamTubeJob*>(job);
//         if(!offerTcpStreamTubeJob) {
//             // Not an OfferTcpStreamTubeJob
//             return;
//         }
//         m_outgoingStreamTubeChannel = offerTcpStreamTubeJob->outgoingStreamTubeChannel();
    }
}


void OfferTcpStreamTube::onTcpServerNewConnection()
{
    kDebug() << "Pending connection found";
    QTcpSocket* socket = m_server->nextPendingConnection();
    connect (socket, SIGNAL(readyRead()),
             this,   SLOT(onDataFromSocket()));
}


void OfferTcpStreamTube::onDataFromSocket()
{
    QIODevice *source = qobject_cast<QIODevice*>(sender());
    QString data = QLatin1String(source->readLine());
    data.remove(QLatin1Char('\n'));
    kDebug() << "New data from socket: " << data;
    if (data == QLatin1String("Hi there!!")) {
        source->write(QByteArray("Hey back mate.\n"));
    } else {
        source->write(QByteArray("Sorry, I have no time for you right now.\n"));
    }
}


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

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

} // end namespace Test
