#include "tipwidget.h"

#include <QLabel>
#include <QTimer>
#include <QGSettings>
#include <QHBoxLayout>
#include <QGraphicsDropShadowEffect>

TipWidget::TipWidget(QWidget *parent) : QDialog(parent)
{
    w = new QWidget(this);
    setWindowFlag(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setModal(true);

    QGraphicsDropShadowEffect * effect = new QGraphicsDropShadowEffect(w);
    effect->setOffset(0, 4);
    effect->setColor(QColor(0, 0, 0, 64));
    effect->setBlurRadius(8);
    w->setGraphicsEffect(effect);
    w->setStyleSheet("QWidget{background-color:#FFFFFF;border-radius:6px;}");
}

TipWidget::~TipWidget()
{
    if (w) {
        delete w;
        w = nullptr;
    }
}

void TipWidget::setLightTheme()
{
    w->setStyleSheet("QWidget{background-color:#FFFFFF;border-radius:6px;}");
}

void TipWidget::setBlackTheme()
{
    w->setStyleSheet("QWidget{background-color:#262626;border-radius:6px;}");
}

void TipWidget::showTip(QString tip, int show_time, QSize size, QWidget *parent, TipWidget::TipType type)
{
    TipWidget tw(parent);
    tw.setFixedSize(size);

    QLabel iconLabel(tw.getWidget());
    iconLabel.setFixedSize(24, 24);

    switch (type) {
    case OK:
        iconLabel.setStyleSheet(QString("border-image:url(:/html/html/img/tips.svg);"));
        break;
    default:
        break;
    }

    QLabel textLabel(tw.getWidget());
    textLabel.setText(tip);
    textLabel.setStyleSheet("font-family: Noto Sans CJK SC; font-size: 14px; font-weight: 400;");
    // QFontMetrics fontWidth(lab_text.font());
    // tw.setFixedSize(fontWidth.width(tip) + 50, fontWidth.height() + 8);

    QHBoxLayout hLayout;
    hLayout.setContentsMargins(0,0,0,0);
    hLayout.addWidget(&iconLabel);
    hLayout.addWidget(&textLabel);
    hLayout.setAlignment(Qt::AlignHCenter);
    tw.getWidget()->setLayout(&hLayout);

    QTimer::singleShot(show_time, [&tw](){
        tw.accept();
    });

    tw.show();
    if (parent) {
        QSize size = (parent->size() - tw.size()) / 2;
        tw.move(parent->mapToGlobal(QPoint(0, 0)) + QPoint(size.width(), size.height()));
    }
    tw.exec();
}

void TipWidget::resizeEvent(QResizeEvent *event)
{
    w->setGeometry(2, 2, size().width() - 4, size().height() - 4);
    return QDialog::resizeEvent(event);
}
