#include "ImgD.h"

#include <QWebElementCollection>
#include <QWebFrame>

ImgD::ImgD() :
    QObject()
{
    connect(&m_WebCtrl, SIGNAL(finished(QNetworkReply*)),
                SLOT(fileDownloaded(QNetworkReply*)));
 
    urlEdit = new QLineEdit;
    button = new QPushButton("Download");
    connect(button,SIGNAL(clicked()),SLOT(download()));
    info = new QLabel;

    QBoxLayout* mainLayout = new QBoxLayout(QBoxLayout::TopToBottom);
    mainLayout -> addWidget(urlEdit);
    mainLayout -> addWidget(button);
    mainLayout -> addWidget(info);
    widg.setLayout(mainLayout);
    
    connect(&view,SIGNAL(loadFinished(bool)),SLOT(startDownload(bool)));
    connect(&view,SIGNAL(loadStarted()),SLOT(start()));
    connect(this, SIGNAL(downloaded(QString)), SLOT(loadImage(QString)));
}
 
ImgD::~ImgD()
{
 
}
 
void ImgD::fileDownloaded(QNetworkReply* pReply)
{
    m_DownloadedData = pReply->readAll();
    pReply->deleteLater();
    emit downloaded((pReply -> url()).toString());
}

void ImgD::download()
{
    url = new QUrl(urlEdit -> text());
    
    view.load(*url);
}

void ImgD::start()
{
    info -> setText("STARTED");
}

void ImgD::startDownload(bool)
{
    QString base = (urlEdit -> text()).left( (urlEdit -> text()).indexOf("/",8) );
    
    QWebElementCollection links;
    links = view.page()->mainFrame()->findAllElements("a[name='expandfunc']");

    foreach (QWebElement paraElement, links)
    {
        QString imageUrl = base + paraElement.attribute("href");
        info -> setText( info -> text() + "\ndownloading.." + imageUrl);
        QNetworkRequest request(imageUrl);
        m_WebCtrl.get(request);
    }

}

void ImgD::loadImage(QString name)
{
    QPixmap image;
    name = name.right(name.size() - name.lastIndexOf("/") - 1);
    info -> setText( info -> text() + "\nsaving.." + name);
    image.loadFromData(m_DownloadedData);
    (image.toImage()).save(name);
}