/* -*- c++ -*-
 *
 * webbrowser.cpp
 *
 * Copyright (C) 2003 Petter Stokke <ummo@hellokitty.com>
 * Copyright (C) 2003,2007 Sebastian Sauer <mail@dipe.org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * 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
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <kdebug.h>
#include <klocale.h>
#include <kguiitem.h>
#include <qprogressbar.h>
#include <kpushbutton.h>
#include <ksqueezedtextlabel.h>
#include <klineedit.h>
#include <QLayout>
#include <QRegExp>
#include <qdatastream.h>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFrame>

#include <fileinfo.h>
#include <serverinfo.h>
#include <shareinfo.h>
#include <searchinfo.h>

#include <donkeyprotocol.h>

#include "kmldonkey.h"
#include "webbrowser.h"
#include "webbrowser.moc"

WebBrowser::WebBrowser(QWidget* parent)
    : QWidget(parent)
{
    hpos = 0;
    initialState = true;

    QVBoxLayout *layout = new QVBoxLayout(this);

    browser = new KHTMLPart(this);
    browser->setJScriptEnabled(false);
    browser->setJavaEnabled(false);
    browser->setMetaRefreshEnabled(false);
    browser->setPluginsEnabled(false);
    connect(browser->browserExtension(), SIGNAL(openUrlRequestDelayed(const KUrl&, const KParts::OpenUrlArguments&, const KParts::BrowserArguments)),
	        this, SLOT(slotUrlSelected(const KUrl&, const KParts::OpenUrlArguments&, const KParts::BrowserArguments)));
    connect(browser, SIGNAL(setStatusBarText(const QString&)), this, SLOT(setStatusBarText(const QString&)));
    connect(browser->browserExtension(), SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)));
    layout->addWidget(browser->widget());

    QHBoxLayout* bottom = new QHBoxLayout();

    backButton = new KPushButton(KGuiItem(QString::null, "back", i18n("Move backward through the page history")), this);
    backButton->setEnabled(false);
    bottom->addWidget(backButton);
    forwardButton = new KPushButton(KGuiItem(QString::null, "forward", i18n("Move forward through the page history")), this);
    forwardButton->setEnabled(false);
    bottom->addWidget(forwardButton);
    homeButton = new KPushButton(KGuiItem(QString::null, "gohome", i18n("Go to the original page")), this);
    homeButton->setEnabled(false);
    bottom->addWidget(homeButton);

    connect(backButton, SIGNAL(clicked()), this, SLOT(backState()));
    connect(forwardButton, SIGNAL(clicked()), this, SLOT(forwardState()));
    connect(homeButton, SIGNAL(clicked()), this, SLOT(goHome()));

    statusbar = new KSqueezedTextLabel(this);
    statusbar->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
    bottom->addWidget(statusbar, 90);

    progressbar = new QProgressBar(this);
    progressbar->setRange(0,100);
    bottom->addWidget(progressbar, 10);
    progressbar->hide();

    layout->addLayout(bottom);
}

WebBrowser::~WebBrowser()
{
    delete browser; // this is needed to prevent crashes (see bugreport #79647)
}

void WebBrowser::slotUrlSelected(const KUrl& url, const KParts::OpenUrlArguments& urlargs, const KParts::BrowserArguments browserargs)
{
    //browser->browserExtension()->setURLArgs(args);
    openURL(url, urlargs, browserargs);
}

void WebBrowser::restoreState(QByteArray& state)
{
    QDataStream s(&state, QIODevice::ReadOnly);
    browser->browserExtension()->restoreState(s);
}

QByteArray WebBrowser::saveState()
{
    QByteArray state;
    QDataStream s(&state, QIODevice::WriteOnly);
    browser->browserExtension()->saveState(s);
    return state;
}

void WebBrowser::pushState()
{
    while (hpos < history.count()) history.pop_back();
    history.append(saveState());
    hpos = history.count();
    forwardButton->setEnabled(false);
    backButton->setEnabled(true);
}

void WebBrowser::backState()
{
    if (hpos <= 0) {
        backButton->setEnabled(false);
        return;
    }
    if (hpos >= history.count()) history.append(saveState());
    hpos--;
    restoreState(history[hpos]);
    backButton->setEnabled(hpos > 0);
    forwardButton->setEnabled(hpos < history.count() - 1);
}

void WebBrowser::forwardState()
{
    if (hpos >= history.count() - 1) {
	forwardButton->setEnabled(false);
	return;
    }
    hpos++;
    restoreState(history[hpos]);
    backButton->setEnabled(hpos > 0);
    forwardButton->setEnabled(hpos < history.count() - 1);
}

void WebBrowser::openURL(const QString& url)
{
    openURL(KUrl(url));
}

void WebBrowser::openURL(const KUrl& url, const KParts::OpenUrlArguments& urlargs, const KParts::BrowserArguments browserargs)
{
    Q_UNUSED(urlargs);
    Q_UNUSED(browserargs);
    if (url.protocol() == "ed2k")
        handleED2K(ED2KURL(url));
    else {
        if (!initialState)
            pushState();
        else {
            initialState = false;
            initialURL = url;
            homeButton->setEnabled(true);
        }
        setStatusBarText(url.url());
        browser->openUrl(url);
    }
}

void WebBrowser::goHome()
{
    if (!initialState)
	openURL(initialURL);
}

void WebBrowser::setStatusBarText(const QString& text)
{
    statusbar->setText(text);
}

void WebBrowser::loadingProgress(int percent)
{
    progressbar->setValue(percent);
    if (percent >= 100)
        progressbar->hide();
    else
        progressbar->show();
}

void WebBrowser::handleED2K(const ED2KURL& url)
{
    if (url.isInvalid()) return;
    KMLDonkey::App->donkey->submitUrl(url.toString());
}

