/* 
 *  Copyright (C) 1999-2000 Bernd Gehrmann
 *                          bernd@physik.hu-berlin.de
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the "Artistic License" which comes with this Kit. 
 *
 * This program 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
 * Artistic License for more details.
 *
 * You should have received a copy of the Artistic License with 
 * this Kit, in the file named "Artistic".  If not, I'll be glad
 * to provide one.
 */


#include <qtabwidget.h>
#include <qvbox.h>
#include <qlayout.h>
#include <qdragobject.h>
#include <qdom.h>
#include <qfile.h>
#include <klocale.h>
#include <kbuttonbox.h>
#include <kiconloader.h>
#include <kdialog.h>
#include <kapp.h>
#include <kmessagebox.h>
#include <kstddirs.h>
#include <kio/netaccess.h>

#include "toplevel.h"
#include "web.h"
#include "ftp.h"
#include "whois.h"
#include "people.h"


TopLevel::TopLevel()
{
    QVBox *vbox = new QVBox(this);
    vbox->setMargin(KDialog::marginHint());
    vbox->setSpacing(KDialog::spacingHint());

    QTabWidget *tab = new QTabWidget(vbox, "tab-widget");
    WebTopLevel *web = new WebTopLevel(tab, "web-widget");
    FtpTopLevel *ftp = new FtpTopLevel(tab, "ftp-widget");
    WhoisTopLevel *whois = new WhoisTopLevel(tab, "whois-widget");
    PeopleTopLevel *person = new PeopleTopLevel(tab, "people-widget");

    tab->addTab(web, i18n("&Web"));
    tab->addTab(ftp, i18n("&Ftp"));
    tab->addTab(whois, i18n("&NIC"));
    tab->addTab(person, i18n("&People"));

    KButtonBox *buttonbox = new KButtonBox(vbox, Horizontal);
    QPushButton *help = buttonbox->addButton(i18n("&Help"));
    connect( help, SIGNAL(clicked()), this, SLOT(help()) );
    buttonbox->addStretch();
    QPushButton *close = buttonbox->addButton(i18n("&Close"));
    connect( close, SIGNAL(clicked()), kapp, SLOT(quit()) );
    buttonbox->layout();
    
    setCentralWidget(vbox);

    kapp->installEventFilter(this);
}
    

TopLevel::~TopLevel()
{}


bool TopLevel::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::DragEnter)
        {
            qDebug("Enter");
            QDragEnterEvent *de = (QDragEnterEvent*) e;
            const char *fmt;
            for (int i=0; (fmt = de->format(i)); i++) 
                qDebug("Drag on %s enter format: %s", o->name(), fmt);
                       
            if (QUriDrag::canDecode(de))
                {
                    de->accept();
                    qDebug("can decode");
                }
            else
                de->ignore();
            return true;
        }
    else if (e->type() == QEvent::DragLeave)
      {
         qDebug("Leave");
         return true;
      }
    else if (e->type() == QEvent::Drop)
        {
            qDebug("drop");
            QDropEvent *de = (QDropEvent*) e;
            QStringList uris;
            QUriDrag::decodeToUnicodeUris(de, uris); 
            QStringList::Iterator it = uris.begin();
            for (; it != uris.end(); ++it)
                {
                    // TODO: Check mimetype
                    KURL url(*it);
                    QString filename;
                    if (url.isLocalFile())
                      filename = url.path();
                    else
                    {
                        if (!KIO::NetAccess::download(url, filename))
                            continue;
                    } 
                    installPlugin(filename);
                    KIO::NetAccess::removeTempFile(filename);
                }
            return true;
        }
    return false;
}


void TopLevel::installPlugin(const QString &filename)
{
    qDebug("Install Plugin %s", filename.latin1());
    QFile file(filename);
    if (!file.open(IO_ReadOnly))
        {
            KMessageBox::sorry(this, i18n("Can't open the file %1").arg(filename));
            return;
        }
    
    uint size = file.size();
    char *buffer = new char[size+1];
    file.readBlock(buffer, size);
    file.close();
    buffer[size] = '\0';
    QString text = QString::fromUtf8(buffer, size);
    delete[] buffer;

    QDomDocument doc;
    if (!doc.setContent(text))
        {
            KMessageBox::sorry(this, i18n("The file %1 does not contain valid XML").arg(filename));
            return;
        }
    if (doc.doctype().name() != "search")
        {
            KMessageBox::sorry(this, i18n("The file %1 does not contain a valid plugin definition,"
                                          "which must have a document type 'search'").arg(filename));
            return;
        }
    QDomElement docel = doc.documentElement();
    if (docel.attribute("name").isEmpty())
        {
            KMessageBox::sorry(this, i18n("The file %1 lacks a name for the plugin.").arg(filename));
            return;
        }
    QString method = docel.attribute("method");
    if (method == "post")
        {
            KMessageBox::sorry(this, i18n("Sending a request with a POST operation is not supported yet."));
            return;
        }
    else if (method != "get" && method != "ldap")
        {
            KMessageBox::sorry(this, i18n("The given method %1 is not supported.").arg(method));
            return;
        }
    if (docel.attribute("action").isEmpty())
        {
            KMessageBox::sorry(this, i18n("The file %1 lacks a URL for the search engine.").arg(filename));
            return;
        }
    QString channel = docel.attribute("channel");
    QString sitetype;
    if (channel != "web")
        sitetype = "web-sites";
    else if (channel == "ftp")
        sitetype = "ftp-sites";
    else if (channel == "people")
        sitetype = "people-sites";
    else
        {
            KMessageBox::sorry(this, i18n("The given channel %1 is not supported.").arg(channel));
            return;
        }
    KURL srcurl(filename);
    KURL desturl(KGlobal::dirs()->saveLocation("data", "libksearch/" + sitetype, true) + "/" + srcurl.filename());
    KIO::NetAccess::copy(srcurl, desturl);
}


void TopLevel::help()
{
    kapp->invokeHTMLHelp("", "");
}
