/*! @file

    @id $Id$
*/
//       1         2         3         4         5         6         7         8
// 45678901234567890123456789012345678901234567890123456789012345678901234567890

#ifndef __SWISSWEBPAGE_HXX__
#define __SWISSWEBPAGE_HXX__

#include <qbrowserlib/log.hxx>
#include <qbrowserlib/pluginfactory.hxx>

#include <QWebPage>
#include <QWebHistory>
#include <QtCore/QProcessEnvironment>

//! @addtogroup qbrowserlib
//! @{

namespace qbrowserlib {

  //! QWebPage with additional features and better default behaviour.
  /*! SwissWebPage is designed to be used by SwissWebView.

      This QWebPage supports the folloing additional features:
      - Handling of plugins through PluginFactory
      - Processing of unsupportedContent
      - Delegation of all links
      - Signals @ref newPage if a new window should be created
      - Set useragent from environment variable @c SWISS_USERAGENT */
  class SwissWebPage: public QWebPage {
      Q_OBJECT;
    Q_SIGNALS:
      void newPage(SwissWebPage*);
    public:
      SwissWebPage(QNetworkAccessManager* net, QObject *parent = 0):
          QWebPage(parent), _net(net) {
        setNetworkAccessManager(_net);
        PluginFactory* pf(new PluginFactory(_net, this));
        assert(connect(pf, SIGNAL(done()), SLOT(back())));
        setPluginFactory(pf);
        setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
        setForwardUnsupportedContent(true);
      }
    public Q_SLOTS:
      void back() {
        history()->back();
      }
    protected:
      virtual QWebPage* createWindow(WebWindowType type) {
        switch (type) {
          case QWebPage::WebBrowserWindow:
          case QWebPage::WebModalDialog: {
            SwissWebPage *page(new SwissWebPage(_net, parent()));
            newPage(page);
            return page;
          } break;
        }
        return 0;
      }
      virtual QString userAgentForUrl(const QUrl& url) const {
        QString add(QProcessEnvironment::systemEnvironment()
                    .value("SWISS_USERAGENT"));
        return QWebPage::userAgentForUrl(url)+(add.size()?" "+add:QString());
      }
      QObject* createPlugin(const QString& classid, const QUrl& url,
                            const QStringList& paramNames,
                            const QStringList& paramValues) {
        TRC; LOG<<"classid:"<<classid
           <<"url:"<<url
           <<"paramNames:"<<paramNames.join(", ")
           <<"paramValues:"<<paramValues.join(", ");
        return QWebPage::createPlugin(classid, url, paramNames, paramValues);
      }
    private:
      QNetworkAccessManager* _net;
  };

}

//! @}
#endif
