#include "eweb.h"
#include "program/progeditorwin.h"
#include <QSpinBox>
#include <QBoxLayout>
#include <QLineEdit>

EWeb::EWeb(EBase *multiWin) : EBase(multiWin) {
    mType = EBase::Web;
    duration = 10;
}
EWeb::EWeb(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) {
    mType = EBase::Web;
    setBaseAttr(json);
    url = json["url"].toString();
    duration = json["duration"].toInt(10);
}

void EWeb::paint(QPainter *painter, const QStyleOptionGraphicsItem *a, QWidget *b) {
    auto inner = innerRect();
    painter->setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform);
    double maskW = holder().width(), maskH = holder().height();
    if(maskW>inner.width() || maskH>inner.height()) {
        double rate = qMin(inner.width() / maskW, inner.height() / maskH);
        maskW *= rate;
        maskH *= rate;
    }
    painter->drawImage(QRectF((inner.width() - maskW)/2, (inner.height() - maskH)/2, maskW, maskH), holder());
    EBase::paint(painter, a, b);
}

QWidget* EWeb::attrWgt() {
    auto wgtAttr = new QWidget();
    auto vBox = new QVBoxLayout(wgtAttr);
    vBox->setContentsMargins(6, 0, 6, 0);
    if(mMultiWin!=nullptr) vBox->setSpacing(3);

    addBaseAttrWgt(vBox);

    auto hBox = new QHBoxLayout;
    hBox->addWidget(new QLabel(tr("Basic Properties")));

    auto line = new QFrame();
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    hBox->addWidget(line, 1);

    vBox->addLayout(hBox);

    hBox = new QHBoxLayout;
    hBox->addSpacing(6);
    hBox->addWidget(new QLabel("URL: "));

    auto url_fd = new QLineEdit(url);
    hBox->addWidget(url_fd);
    connect(url_fd, &QLineEdit::textChanged, this, [this](const QString &text) {
        url = text;
    });
    vBox->addLayout(hBox);

    hBox = new QHBoxLayout();
    hBox->addSpacing(6);
    hBox->addWidget(new QLabel(tr("Play Duration")+": "));

    auto dur_fd = new QSpinBox();
    dur_fd->setRange(1, 99999);
    dur_fd->setValue(duration);
    connect(dur_fd, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) {
        duration = value;
    });
    hBox->addWidget(dur_fd);

    hBox->addWidget(new QLabel(tr("s")));
    hBox->addStretch();

    vBox->addLayout(hBox);
    vBox->addStretch();
    return wgtAttr;
}

QJsonObject EWeb::attrJson() const {
    QJsonObject oRoot;
    addBaseAttr(oRoot);
    oRoot["elementType"] = "Web";
    oRoot["url"] = url;
    oRoot["duration"] = duration;
    return oRoot;
}
