#include "basedlg.h"
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <QIcon>

BaseDlg::BaseDlg(QWidget *parent) : QDialog(parent) {
    setWindowFlag(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
}

void BaseDlg::paintEvent(QPaintEvent *e) {
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing);
    QPainterPath path = QPainterPath();
    path.addRoundedRect(0.5, 0.5, width()-1, height()-1, roundRadius, roundRadius);
    painter.fillPath(path, palette().window());
    painter.strokePath(path, isActive ? borderPenAct : borderPenUnact);
    QString title = windowTitle();
    if(! icon.isNull()) painter.drawPixmap(iconPos, icon);
    if(! title.isEmpty()) {
        static const QPen penTitleAct(Qt::black);
        static const QPen penTitleUnact(Qt::darkGray);
        painter.setPen(isActive ? penTitleAct : penTitleUnact);
        painter.drawText(icon.isNull() ? iconPos.x() : iconPos.x()+icon.width()+6, iconPos.y()+12, title);
    }
    QDialog::paintEvent(e);
}

void BaseDlg::mousePressEvent(QMouseEvent *e) {
    if(e->button() != Qt::LeftButton) return;
    pressRel = pos() - e->globalPos();
}
void BaseDlg::mouseReleaseEvent(QMouseEvent *e) {
    if(e->button() == Qt::LeftButton) pressRel *= 0;
}
void BaseDlg::mouseMoveEvent(QMouseEvent *e) {
    if(e->buttons() & Qt::LeftButton) {
        if(pressRel.isNull()) return;
        if(isMaximized()) return;
        move(pressRel + e->globalPos());
    }
}
#ifdef Q_OS_WINDOWS
#include <windows.h>
#if(QT_VERSION_MAJOR > 5)
    bool BaseDlg::nativeEvent(const QByteArray &eventType, void *message, qintptr *) {
#else
    bool BaseDlg::nativeEvent(const QByteArray &eventType, void *message, long *) {
#endif
    if(eventType=="windows_generic_MSG"){
        MSG *msg = (MSG*)message;
        if(msg->message==WM_NCACTIVATE){
            isActive = msg->wParam;
            update();
        }
    }
    return false;
}
#endif
