#include "frmimgshow.h"

FrmImgShow::FrmImgShow(QString& url, QWidget *parent) : QWidget(parent)
{
    initForm();
    initForm();
    initManager();
    this->url = url;
    manager->get(QNetworkRequest(QUrl(url)));
}

bool FrmImgShow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == btnCopy) {
        if (event->type() == QEvent::Enter) {
            btnCopy->setIcon(QIcon(QPixmap(":/qrc/image/copy_blue.png")));
            return true;
        }
        else if (event->type() == QEvent::Leave) {
            btnCopy->setIcon(QIcon(QPixmap(":/qrc/image/copy_white.png")));
            return true;
        }
        else {
            return false;
        }
    }

    if (watched == btnDelete) {
        if (event->type() == QEvent::Enter) {
            btnDelete->setIcon(QIcon(QPixmap(":/qrc/image/delete_red.png")));
            return true;
        }
        else if (event->type() == QEvent::Leave) {
            btnDelete->setIcon(QIcon(QPixmap(":/qrc/image/delete_white.png")));
            return true;
        }
        else {
            return false;
        }
    }

    return QWidget::eventFilter(watched, event);
}

void FrmImgShow::onFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray imageData = reply->readAll();
        QPixmap pix;
        pix.loadFromData(imageData);
        this->labImg->setPixmap(pix);
    }
}

void FrmImgShow::initForm()
{
    labImg = new QLabel();
    btnCopy = new QToolButton();
    btnDelete = new QToolButton();
    horizenSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    hLayout = new QHBoxLayout();
    vLayout = new QVBoxLayout();

    hLayout->addWidget(btnCopy);
    hLayout->addSpacerItem(horizenSpacer);
    vLayout->addWidget(labImg);
    vLayout->addLayout(hLayout);
    this->setLayout(vLayout);

    btnCopy->setIcon(QIcon(QPixmap(":/qrc/image/copy_white.png")));
    btnDelete->setIcon(QIcon(QPixmap(":/qrc/image/delete_white.png")));
    btnCopy->setFixedSize(32, 32);
    btnCopy->setCursor(Qt::PointingHandCursor);
}

void FrmImgShow::initWidget()
{
    btnCopy->installEventFilter(this);
    btnDelete->installEventFilter(this);
}

void FrmImgShow::initManager()
{
    manager = new QNetworkAccessManager();
    QClipboard* clipboard = QGuiApplication::clipboard();
    connect(manager, &QNetworkAccessManager::finished,
            this, &FrmImgShow::onFinished);

    connect(btnCopy, &QToolButton::clicked, [&](){
        clipboard->setText(this->url);
    });
}
