/*****************************************************************

Copyright (c) 2000, 2001 Matthias Hoelzer-Kluepfel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/


#include <qfile.h>
#include <qtextstream.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qcheckbox.h>
#include <qpushbutton.h>


#include <kapplication.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <klocale.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kaboutdata.h>
#include <ktextbrowser.h>
#include <kiconloader.h>
#include <kseparator.h>
#include <kstdguiitem.h>
#include <kpushbutton.h>

#include <kdebug.h>

#include "ktip.h"


KTipDatabase::KTipDatabase(const QString &_tipFile)
{
  QString tipFile = _tipFile;
  if (tipFile.isEmpty())
    tipFile = QString::fromLatin1(KGlobal::instance()->aboutData()->appName()) + "/tips";

  loadTips(tipFile);

  if (tips.count())
    current = kapp->random() % tips.count();
}


// if you change something here, please update the script
// preparetips, which depends on extracting exactly the same
// text as done here.
void KTipDatabase::loadTips(const QString &tipFile)
{
    QString fileName = locate("data", tipFile);

    if (fileName.isEmpty())
    {
        kdDebug() << "can't find '" << tipFile.latin1() << "' in standard dirs" << endl;
        return;
    }

    QFile file(fileName);
    if (!file.open(IO_ReadOnly))
    {
        kdDebug() << "can't open '" << fileName.latin1() << "' for reading" << endl;
        return;
    }

    tips.clear();

    QString content = file.readAll();

    int pos = -1;
    while ((pos = content.find("<html>", pos + 1, false)) != -1)
    {
        QString tip = content.mid(pos + 6, content.find("</html>", pos, false) - pos - 6);
        tips.append(tip);
    }

    file.close();
}


void KTipDatabase::nextTip()
{
  if (tips.count() == 0)
    return ;
  current += 1;
  if (current >= (int) tips.count())
    current = 0;
}


void KTipDatabase::prevTip()
{
  if (tips.count() == 0)
    return ;
  current -= 1;
  if (current < 0)
    current = tips.count() - 1;
}


QString KTipDatabase::tip() const
{
  return QString::fromLatin1("<html>%1</html>").arg(i18n(tips[current].latin1()));
}



KTipDialog *KTipDialog::_instance = 0;


KTipDialog::KTipDialog(KTipDatabase *db, QWidget *parent, const char *name)
  : KDialog(parent, name)
{
  _database = db;

  setCaption(i18n("Tip of the Day"));
  setIcon(KGlobal::iconLoader()->loadIcon("ktip", KIcon::Small));

  QVBoxLayout *vbox = new QVBoxLayout(this, marginHint(), spacingHint());

  QHBoxLayout *hbox = new QHBoxLayout(vbox, 0, 0);

  QLabel *bulb = new QLabel(this);
  bulb->setPixmap(locate("data", "kdeui/pics/ktip-bulb.png"));
  hbox->addWidget(bulb);

  QLabel *titlePane = new QLabel(this);
  titlePane->setBackgroundPixmap(locate("data", "kdeui/pics/ktip-background.png"));
  titlePane->setText(i18n("Did you know...?\n"));
  titlePane->setFont(QFont(KGlobalSettings::generalFont().family(), 20,  QFont::Bold));
  titlePane->setAlignment(QLabel::AlignCenter);
  hbox->addWidget(titlePane,100);

  _tipText = new KTextBrowser(this);
  vbox->addWidget(_tipText);
  _tipText->installEventFilter(this);

  KSeparator* sep = new KSeparator( KSeparator::HLine, this);
  vbox->addWidget(sep);

  hbox = new QHBoxLayout(vbox);

  _tipOnStart = new QCheckBox(i18n("&Show on start"), this);
  hbox->addWidget(_tipOnStart);
  hbox->addStretch();

  QPushButton *next = new QPushButton(i18n("&Next"), this);
  hbox->addWidget(next);

  KPushButton *ok = new KPushButton(KStdGuiItem::close(), this);
  hbox->addWidget(ok);
  ok->setDefault(true);

  connect(ok, SIGNAL(clicked()), this, SLOT(accept()));
  connect(next, SIGNAL(clicked()), this, SLOT(nextTip()));
  connect(_tipOnStart, SIGNAL(toggled(bool)), this, SLOT(showOnStart(bool)));

  KConfigGroup config(KGlobal::config(), "TipOfDay");
  _tipOnStart->setChecked(config.readBoolEntry("RunOnStart", true));
}


void KTipDialog::showTip(const QString &tipFile, bool force)
{
  showTip(qApp->mainWidget(), tipFile, force);
}


void KTipDialog::showTip(QWidget *parent,const QString &tipFile, bool force)
{
  if (!force)
  {
    KConfigGroup config(KGlobal::config(), "TipOfDay");
    if (!config.readBoolEntry("RunOnStart", true))
      return;
  }

  if (!_instance)
    _instance = new KTipDialog(new KTipDatabase(tipFile), parent);

  _instance->nextTip();
  _instance->show();
  _instance->raise();
}


void KTipDialog::nextTip()
{
  _database->nextTip();
  _tipText->setText(_database->tip());
}


void KTipDialog::showOnStart(bool on)
{
  setShowOnStart(on);
}


void KTipDialog::setShowOnStart(bool on)
{
  KConfigGroup config(KGlobal::config(), "TipOfDay");
  config.writeEntry("RunOnStart", on);
  config.sync();
}


bool KTipDialog::eventFilter(QObject *o, QEvent *e)
{
  if ( o == _tipText && e->type()== QEvent::KeyPress &&
      ( ( (QKeyEvent *)e)->key() == Key_Return ||
	( (QKeyEvent *)e)->key() == Key_Space ) )
    accept();
    
  // If the user presses Return or Space, we close the dialog as if the
  // default button was pressed even if the KTextBrowser has the keyboard
  // focus. This could have the bad side-effect that the user cannot use the
  // keyboard to open urls in the KTextBrowser, so we just let it handle
  // the key event _additionally_. (Antonio)
  return QWidget::eventFilter( o, e );
}

void KTipDialog::virtual_hook( int id, void* data )
{ KDialog::virtual_hook( id, data ); }

#include "ktip.moc"
