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

Copyright (c) 2000, 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 <stdlib.h>


#include <qapplication.h>
#include <qframe.h>
#include <qcheckbox.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <ktextbrowser.h>
#include <qlabel.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qhbox.h>

#include <kapplication.h>
#include <kuniqueapplication.h>
#include <kaboutdata.h>
#include <kdebug.h>
#include <kcmdlineargs.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfig.h>
#include <kmessagebox.h>
#include <kiconloader.h>
#include <kseparator.h>
#include <kstandarddirs.h>
#include <kwin.h>
#include <qdesktopwidget.h>
#include <qcursor.h>

#include <kdebug.h>

#include "ktipwindow.moc"


TipWindow::TipWindow()
  : QDialog(0,0,false)
{
    KWin::setState( winId(), NET::StaysOnTop );
    setCaption(i18n("Kandalf's Useful Tips"));

    QVBoxLayout *vbox = new QVBoxLayout(this, 4);

    QHBox *hbox = new QHBox(this);
    hbox->setSpacing(0);
    hbox->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    vbox->addWidget(hbox);

    QHBox *tl = new QHBox(hbox);
    tl->setMargin(7);
    tl->setBackgroundColor(QColor(49, 121, 172));
    tl->setMinimumWidth(380);
    hbox->setStretchFactor(tl, 3);

    QHBox *topLeft = new QHBox(tl);
    topLeft->setMargin(15);
    QColor bgColor(213, 222, 238);
    topLeft->setBackgroundColor(bgColor);

    text = new KTextBrowser(topLeft);
    text->mimeSourceFactory()->addFilePath(KGlobal::dirs()->findResourceDir("data", "kdewizard/pics")+"kdewizard/pics/");
    text->setFrameStyle(QFrame::NoFrame | QFrame::Plain);
    text->setHScrollBarMode(QScrollView::AlwaysOff);
    text->installEventFilter(this);
    QStringList icons = KGlobal::dirs()->resourceDirs("icon");
    QStringList::Iterator it;
    for (it = icons.begin(); it != icons.end(); ++it)
        text->mimeSourceFactory()->addFilePath(*it);
#if QT_VERSION < 300
#warning ### set colors
    QColorGroup colors;
    colors.setBrush(QColorGroup::Base, QBrush(bgColor));
    colors.setColor(QColorGroup::Highlight, QColor(49, 121, 172));
    colors.setColor(QColorGroup::HighlightedText, Qt::white);
    text->setPaperColorGroup(colors);
#endif

    QLabel *l = new QLabel(hbox);
    l->setPixmap(locate("data", "kdewizard/pics/wizard_small.png"));
    l->setBackgroundColor(QColor(49, 121, 172));
    l->setAlignment(Qt::AlignRight | Qt::AlignBottom);
    hbox->setStretchFactor(l, 1);

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

    QHBoxLayout *hbox2 = new QHBoxLayout(vbox, 4);

    startup = new QCheckBox(i18n("&Show Tips on Startup"), this);
    hbox2->addWidget(startup, 1);

    prev = new QPushButton(i18n("&Previous"), this);
    hbox2->addWidget(prev);

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

    ok = new QPushButton(i18n("&Close"), this);
    ok->setDefault(true);
    hbox2->addWidget(ok);

    connect(next, SIGNAL(clicked()), this, SLOT(nextTip()));
    connect(prev, SIGNAL(clicked()), this, SLOT(prevTip()));
    connect(ok, SIGNAL(clicked()), this, SLOT(accept()));

    connect(startup, SIGNAL(clicked()), this, SLOT(startupClicked()));

    QSize sh = sizeHint();
    QRect rect = QApplication::desktop()->screenGeometry(QApplication::desktop()->screenNumber(QCursor::pos()));
    int w = rect.x() + (rect.width() - sh.width())/2;
    int h = rect.y() + (rect.height() - sh.height())/2;
    move(w, h);
    loadTips();

    KConfig *config = new KConfig("kdewizardrc", true);
    config->setGroup("General");
    startup->setChecked(config->readBoolEntry("TipsOnStart", true));
    delete config;

    if (tips.count()) {
        current = kapp->random() % tips.count();
    } else {
        prev->setEnabled(false);
        next->setEnabled(false);
    }
}


void TipWindow::done( int )
{
    kapp->quit();
}


void TipWindow::startupClicked()
{
    KConfig *config = new KConfig("kdewizardrc");
    config->setGroup("General");
    config->writeEntry("TipsOnStart", startup->isChecked());
    delete config;
}


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

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

    QFile file(fileName);
    if (!file.open(IO_ReadOnly))
    {
	kdDebug() << "can't open '" << fileName << "' 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);
	if (tip.startsWith("\n"))
	    tip = tip.mid(1);
	tips.append(tip);
    }

    file.close();    
}

void TipWindow::nextTip()
{
    if (tips.count()==0)
        return;
    current += 1;
    if (current >= (int) tips.count())
        current = 0;
    text->setText(QString("<qt bgcolor=\"%1\">%2</qt>").arg(colorGroup().color(QColorGroup::Base).name()).arg(i18n(tips[current].utf8())));
}


void TipWindow::prevTip()
{
    if (tips.count()==0)
        return;
    current -= 1;
    if (current < 0)
        current = tips.count()-1;
    text->setText(QString("<qt bgcolor=\"%1\">%2</qt>").arg(colorGroup().color(QColorGroup::Base).name()).arg(i18n(tips[current].utf8())));
}

bool TipWindow::eventFilter(QObject *o, QEvent *e)
{
    if ( 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 );
}

TipApp::TipApp() : KUniqueApplication()
{
    window = new TipWindow;
    window->show();

    setMainWidget(window);

    connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit()));
}


TipApp::~TipApp()
{
    delete window;
}


static const char *description = I18N_NOOP("Kandalf's tips");

int main(int argc, char *argv[])
{
    KAboutData aboutData("ktip", I18N_NOOP("KTip"),
                         "0.2", description, KAboutData::License_GPL,
                         "(c) 1998-2000, KDE Developers");
    KCmdLineArgs::init( argc, argv, &aboutData );
    KUniqueApplication::addCmdLineOptions();

    if (!KUniqueApplication::start())
        exit(-1);

    TipApp app;

    return app.exec();
}
