/* 
 *  Copyright (C) 1999 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 <stdlib.h>
#include <iostream.h>

#include <qlabel.h>
#include <qlineedit.h>
#include <qlistview.h>
#include <qmessagebox.h>
#include <qheader.h>
#include <qlayout.h>

#include <kapp.h>
#include <kbuttonbox.h>
#include <klocale.h>
#include <kstddirs.h>
#include <khtml.h>

#include <websearch.h>

#include "resultview.h"
#include "toplevel.h"


TopLevel::TopLevel() {
  man = new WebSiteManager();

  setCaption(i18n("Search on the Web"));

  QWidget *mainwidget = new QWidget( this );
  QBoxLayout *layout = new QVBoxLayout(mainwidget, 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:"), mainwidget);
  grid->addWidget(wordslabel, 0, 0);

  wordsedit = new QLineEdit(mainwidget);
  wordsedit->setFocus();
  grid->addWidget(wordsedit, 0, 1);

  QLabel *siteslabel = new QLabel(i18n("Where:"), mainwidget);
  grid->addWidget(siteslabel, 2, 0);

  sitebox = new QListView(mainwidget);
  sitebox->setFrameStyle( QFrame::Panel | QFrame::Sunken );  
  sitebox->header()->hide();
  sitebox->addColumn(i18n("Sites"));

  QDictIterator<Site> it(man->siteDict());
  for (; it.current(); ++it){
    qDebug( "Adding " + it.current()->description );
    QCheckListItem *i = new QCheckListItem(sitebox,
					   it.currentKey(), QCheckListItem::CheckBox);
    i->setPixmap(0, locate( "data", "columbo/pics/" + it.current()->icon));
  }
  grid->addWidget(sitebox, 2, 1);

  KButtonBox *buttonbox = new KButtonBox(mainwidget, KButtonBox::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:"), mainwidget);
  layout->addWidget(foundlabel);

  resultbox = new ResultView(mainwidget);
  layout->addWidget(resultbox, 10);

  layout->addSpacing(10);

  htmlview = new KHTMLWidget(mainwidget);
  htmlview->setUnderlineLinks(false); // doesn't make sense if they're not selectable
  htmlview->setMinimumSize(100, 60);
  layout->addWidget(htmlview, 1);
    
  layout->activate();

  connect( resultbox, SIGNAL(urlActivated(QString)),
	   this, SLOT(urlActivated(QString)) );
  connect( resultbox, SIGNAL(detailsActivated(QString)),
	   this, SLOT(detailsActivated(QString)) );

  jobs.setAutoDelete(true);

  setCentralWidget( mainwidget );
}


TopLevel::~TopLevel() {
}


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


void TopLevel::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(static_cast<WebSite*>(man->find(cb->text())));
      connect( job, SIGNAL(foundItem(QString,QString,QString,int,QString)),
	       this, SLOT(processItem(QString,QString,QString,int,QString)) );
      connect( job, SIGNAL(sigFinished(int)),
	       this, SLOT(slotFinished(int)) );
      connect( job, SIGNAL(sigError(int,int,const char*)),
	       this, SLOT(slotError(int,int,const char*)) );
	    
      job->query(searchtext);
      jobs.append(new int(job->id()));
    }
  }
}


void TopLevel::slotFinished(int id) {
  int *ip;
  for ( ip = jobs.first(); ip != 0; ip = jobs.next() ) {
    if (*ip == id) {
	jobs.remove();
	break;
    }
  }
  updateButtons();
}

    
void TopLevel::slotCancel() {
  QListIterator<int> it(jobs);
  for (; it.current(); ++it) {
    KIOJob::find(*it.current())->kill();
  }
  jobs.clear();
  updateButtons();
}


void TopLevel::slotError(int id, int errid, const char *errortext) {
  QMessageBox::warning(this, "Columbo",
		       KIO::kioErrorString(errid, errortext));
  jobs.remove(&id);
}


void TopLevel::processItem(QString icon, QString name, QString url,
			   int relevance, QString details) {
  resultbox->insertItem(icon, name, url, relevance, details);
  QString str;
  str.setNum(resultbox->childCount());
  str.append(i18n(" matches"));
  str.prepend(i18n("Found "));
  foundlabel->setText(str);
}


void TopLevel::urlActivated(QString url) {
  cout << "Url activated " << url << endl;
  system(QString("kfmclient openURL '" + url + "'"));
}


void TopLevel::detailsActivated(QString details) {
  cout << "Details activated " << details << endl;
  htmlview->begin();
  htmlview->write("<html>");
  htmlview->write(details);
  //     htmlview->parse();
  htmlview->end();
}
