#include "titlebar.h"

#include <QToolButton>
#include <QLabel>
#include <QHBoxLayout>
#include <QDebug>
#include <QLinearGradient>
#include <QPainter>

TitleBar::TitleBar(QMainWindow *parent)
    : FramelessTitleBar(parent)
    , QWidget(parent)
{
    parent->setAttribute(Qt::WA_StyledBackground, true);
    parent->setWindowFlags(Qt::WindowSystemMenuHint |
                           Qt::WindowMinimizeButtonHint |
                           Qt::WindowMaximizeButtonHint |
                           Qt::FramelessWindowHint |
                           Qt::Window
                           );

    parent->setMenuWidget(this);
    parent->setMouseTracking(true);
    parent->raise();
    parent->activateWindow();

    initUI();
}

void TitleBar::setTitleBarBgColor(const QColor &color1, const QColor &color2, const QColor &color3)
{
    mBarColor1 = color1;
    mBarColor2 = color2;
    mBarColor2 = color3;
}

void TitleBar::setLogoButtonSize(int w, int h)
{
    FramelessTitleBar::logoButton()->setIconSize(QSize(w, h));
}

void TitleBar::setTitleFontSizeAndColor(int size, const QColor &color, bool bold)
{
    QString strColor = QString("color: %1;")
                           .arg(color.name());
    QString strFont = bold ? QString("font: bold %1px;").arg(size) : QString("font: %1px;").arg(size);
    FramelessTitleBar::titleLabel()->setStyleSheet(strColor + strFont);
}

void TitleBar::paintEvent(QPaintEvent* e)
{
    // 不知道为什么样式表不起作用，所以只能重写paintEvent函数，实现标题栏的颜色
    QPainter p(this);

    QLinearGradient graient(0, 0, this->rect().width(), this->rect().height());
    graient.setColorAt(0, mBarColor1);
    graient.setColorAt(0.5, mBarColor2);
    graient.setColorAt(1, mBarColor3);
    p.setBrush(graient);
    p.setPen(Qt::transparent);

    p.drawRect(this->rect());
    p.end();
}

void TitleBar::initUI()
{
    mBarColor1 = "#949B8D";
    mBarColor2 = "#475048";
    mBarColor3 = "#8D9487";

    FramelessTitleBar::setTitleWidget(this);

    FramelessTitleBar::setCloseBySystemButton(true);
    //FramelessTitleBar::logoButton()->setIconSize(QSize(50, 50));

    QHBoxLayout *layout = new QHBoxLayout();
    layout->setContentsMargins(1, 1, 1, 1);
    layout->setSpacing(0);
    layout->addWidget(FramelessTitleBar::logoButton());
    //layout->addStretch();
    layout->addWidget(FramelessTitleBar::titleLabel());
    layout->addStretch();
    layout->addWidget(FramelessTitleBar::systemToolBar());
    this->setLayout(layout);

}
