/* 
 *  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 <qmessagebox.h>
#include <qlayout.h>

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

#include <newssearch.h>

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


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

  setCaption(i18n("Search News"));

  QWidget *mainwidget = new QWidget( this );

  QBoxLayout *layout = new QVBoxLayout(mainwidget, 10, 4);
  QFontMetrics fm(fontMetrics());

  QGridLayout *grid = new QGridLayout(3, 4, 4);
  layout->addLayout(grid, 0);
  grid->setColStretch(0, 0);
  grid->setColStretch(1, 10);
  grid->setColStretch(2, 0);
  grid->addColSpacing(2, 10);
  grid->addRowSpacing(1, 15);
  grid->setRowStretch(1, 0);

  QLabel *wordslabel = new QLabel(i18n("What:"), mainwidget);
  wordslabel->setMinimumSize(wordslabel->sizeHint());
  grid->addWidget(wordslabel, 0, 0);

  wordsedit = new QLineEdit(mainwidget);
  wordsedit->setFocus();
  wordsedit->setFixedHeight(wordsedit->sizeHint().height());
  grid->addWidget(wordsedit, 0, 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);
  foundlabel->setFixedHeight(foundlabel->sizeHint().height());
  layout->addWidget(foundlabel);

  resultbox = new ResultView(mainwidget);
  resultbox->setMinimumSize(100, fm.lineSpacing()*20);
  layout->addWidget(resultbox, 10);

#if 0
  layout->addSpacing(10);

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

  connect( resultbox, SIGNAL(urlActivated(QString)),
	   this, SLOT(urlActivated(QString)) );
#if 0
  connect( resultbox, SIGNAL(detailsActivated(QString)),
	   this, SLOT(detailsActivated(QString)) );
#endif

  jobs.setAutoDelete(true);

  setView( mainwidget );
}


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);
  }

  NewsSearch *job = new NewsSearch(static_cast<NewsSite*>(man->find("Deja")));
  connect( job, SIGNAL(foundItem(QString,QString,QString,QString,QString)),
	   this, SLOT(processItem(QString,QString,QString,QString,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 date, QString subject, QString url,
			   QString forum, QString author) {
  resultbox->insertItem(date, subject, url, forum, author);
  QString str;
  str.setNum(resultbox->childCount());
  str.append(i18n(" matches"));
  str.prepend(i18n("Found "));
  foundlabel->setText(str);
}


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


#if 0
void TopLevel::detailsActivated(QString details) {
  qDebug( "Details activated " + details );
}
#endif
