/*! @file

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

#ifndef OPENFROMURL_HXX
#define OPENFROMURL_HXX

#include <ui_openfromurl.hxx>
#include <QDialog>
#include <QNetworkAccessManager>
#include <QNetworkReply>

class OpenFromURL: public QDialog, public Ui::OpenFromURL {
    Q_OBJECT;
  public:
    OpenFromURL(QWidget* p): QDialog(p) {
      setupUi(this);
    }
    QString url() {
      return _url->currentText();
    }
    void read() {
      QNetworkReply* reply
        (_net.head(QNetworkRequest(QUrl("https://"+_url->currentText()))));
      connect(reply, SIGNAL(finished()), SLOT(finished()));
      connect(reply, SIGNAL(encrypted()), SLOT(encrypted()));
      connect(reply, SIGNAL(sslErrors(const QList<QSslError>&)),
              SLOT(sslErrors(const QList<QSslError>&)));
      connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
              SLOT(error(QNetworkReply::NetworkError)));
    }
  signals:
    void certificate(QUrl, QSslCertificate);
  protected slots:
    void on__buttons_accepted() {
      _url->addItem(_url->currentText());
    }
    void finished() {
      qDebug()<<"finished";
      QNetworkReply* reply(dynamic_cast<QNetworkReply*>(sender()));
      QList<QSslCertificate> certs(reply->sslConfiguration()
                                   .peerCertificateChain());
      qDebug()<<"number of peer certificates: "<<certs.size();
      if (certs.size()) {
        Q_FOREACH(QSslCertificate cert, certs) { 
          certificate(reply->url(), cert); 
        }
      } else {
        QSslCertificate cert(reply->sslConfiguration().peerCertificate());
        if (!cert.isNull()) {
          certificate(reply->url(), cert);
        } else {
          qDebug()<<"no peer certificate found";
        }
      }
    }
    void encrypted() {
      qDebug()<<"encrypted";
    }
    void sslErrors(const QList<QSslError>& errors) {
      qDebug()<<"sslErrors";
    }
    void error(QNetworkReply::NetworkError code) {
      qDebug()<<"error";
    }
  private:
    QNetworkAccessManager _net;
};

#endif
