/* 
 *  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 <qlabel.h>
#include <qlineedit.h>
#include <qlistview.h>
#include <qheader.h>
#include <qlayout.h>

#include <kapp.h>
#include <kbuttonbox.h>
#include <klocale.h>
#include <kstddirs.h>
#include <khtml_part.h>
#include <khtmlview.h>

#include "webresults.h"
#include "web.h"


WebTopLevel::WebTopLevel(QWidget *parent, const char *name)
    : QWidget(parent, name)
{
    setAcceptDrops(true);

    man = new WebSiteManager();
    
    QBoxLayout *layout = new QVBoxLayout(this, 10, 4);
    
    QGridLayout *grid = new QGridLayout(3, 4, 4);
    layout->addLayout(grid, 1);
    grid->setColStretch(0, 0);
    grid->setColStretch(1, 10);
    grid->setColStretch(2, 0);
    grid->addColSpacing(2, 10);
    grid->addRowSpacing(1, 5);
    grid->setRowStretch(1, 0);
    
    QLabel *wordslabel = new QLabel(i18n("What:"), this);
    grid->addWidget(wordslabel, 0, 0);
    
    wordsedit = new QLineEdit(this);
    wordsedit->setFocus();
    grid->addWidget(wordsedit, 0, 1);
    
    QLabel *siteslabel = new QLabel(i18n("Where:"), this);
    grid->addWidget(siteslabel, 2, 0);
    
    sitebox = new QListView(this);
    sitebox->setFrameStyle( QFrame::Panel | QFrame::Sunken );  
    sitebox->header()->hide();
    sitebox->addColumn(i18n("Sites"));
    
    QStringList list = man->siteList();
    QStringList::Iterator it();
    for (QStringList::Iterator it = list.begin(); it != list.end(); ++it)
        new QCheckListItem(sitebox, *it, QCheckListItem::CheckBox);
    
    grid->addWidget(sitebox, 2, 1);
    
    KButtonBox *buttonbox = new KButtonBox(this, Vertical);
    searchbutton = buttonbox->addButton(i18n("&Search"));
    searchbutton->setDefault(true);
    connect( searchbutton, SIGNAL(clicked()), SLOT(slotSearch()) );
    
    cancelbutton = buttonbox->addButton(i18n("Cancel"));
    connect( cancelbutton, SIGNAL(clicked()), SLOT(slotCancel()) );
    cancelbutton->setEnabled(false);
    buttonbox->layout();
    grid->addMultiCellWidget(buttonbox, 0, 2, 3, 3);
    
    layout->addSpacing(10);
    
    foundlabel = new QLabel(i18n("Found:"), this);
    layout->addWidget(foundlabel);
    
    resultbox = new WebResultView(this);
    layout->addWidget(resultbox, 10);
    
    layout->addSpacing(10);
    
    htmlpart = new KHTMLPart(this);
    htmlpart->view()->setMinimumSize(100, 60);
    layout->addWidget(htmlpart->view(), 1);
    
    connect( resultbox, SIGNAL(urlActivated(const QString &)),
             this, SLOT(urlActivated(const QString &)) );
    connect( resultbox, SIGNAL(detailsActivated(const QString &)),
             this, SLOT(detailsActivated(const QString &)) );
}


WebTopLevel::~WebTopLevel()
{}


void WebTopLevel::updateButtons()
{
    bool hasjobs = !jobs.isEmpty();
    searchbutton->setEnabled(!hasjobs);
    cancelbutton->setEnabled(hasjobs);
}


void WebTopLevel::slotSearch()
{
    int n;
    QString searchtext = wordsedit->text();
    while ( (n = searchtext.find('\n')) != -1) 
        searchtext.remove(n, 1);
    
    // Lookup checked sites
    QCheckListItem *cb = static_cast<QCheckListItem*>(sitebox->firstChild());
    for (; cb; cb =  static_cast<QCheckListItem*>(cb->nextSibling()))
        if (cb->isOn())
            {
                WebSearch *job = new WebSearch(man->find(cb->text()), searchtext);
                jobs.append(job);
                connect( job, SIGNAL(foundItem(const QString&,const QString&,const QString&,int,const QString&)),
                         this, SLOT(processItem(const QString&,const QString&,const QString&,int,const QString&)) );
                connect( job, SIGNAL(result(KIO::Job*) ),
                         this, SLOT(slotResult(KIO::Job*)) );
            }

    updateButtons();
}


void WebTopLevel::slotCancel()
{
    QListIterator<WebSearch> it(jobs);
    for (; it.current(); ++it)
        it.current()->kill();
}


void WebTopLevel::slotResult(KIO::Job *job)
{
    if (job->error())
        job->showErrorDialog(this);
    jobs.remove(static_cast<WebSearch*>(job));
        
    updateButtons();
}

    
void WebTopLevel::processItem(const QString &sitename, const QString &title,
                              const QString &url, int relevance, const QString &details)
{
    qDebug("Sitename: %s", sitename.latin1());
    resultbox->insertItem("" /*icon?*/, title, url, relevance, details);

    QString str = i18n("Found %1 matches")
      .arg(KGlobal::locale()->formatNumber(resultbox->childCount(), 0));
    foundlabel->setText(str);
}


void WebTopLevel::urlActivated(const QString &url)
{
    qDebug( "Url activated %s", url.latin1());
    kapp->invokeBrowser(url);
}


void WebTopLevel::detailsActivated(const QString &details)
{
    qDebug("Details activated %s", details.latin1());
    htmlpart->begin();
    htmlpart->write("<html>");
    htmlpart->write(details);
    htmlpart->end();
}
