#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMenu>
#include <QDebug>
#include <QTimer>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->popupButton, SIGNAL(clicked()), this, SLOT(popupButtonPressed()));
    connect(ui->grabButton, SIGNAL(clicked()), this, SLOT(grabButtonPressed()));
    connect(ui->grabButton2, SIGNAL(clicked()), this, SLOT(grabButton2Pressed()));
    connect(ui->modalButton, SIGNAL(clicked()), this, SLOT(modalButtonPressed()));

    QMenu *menu = new QMenu(this);
    menu->addAction(tr("&First Item"));
    menu->addAction(tr("&Second Item"));
    menu->addAction(tr("&Third Item"));
    menu->addAction(tr("F&ourth Item"));
    ui->popupButton->setMenu(menu);

    setWindowTitle("Mouse autograb test application, Qt" + QString::number(QT_VERSION >> 16));

    QPalette pal = palette();
    pal.setColor(QPalette::Active, QPalette::Window, Qt::yellow);
    pal.setColor(QPalette::Inactive, QPalette::Window, Qt::yellow);
    ui->dialogLaunchWidget->setPalette(pal);
    ui->dialogLaunchWidget->setAutoFillBackground(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::popupButtonPressed()
{
    qDebug() << "Popup pressed";
}

static bool isCurrentlyGrabbing = false;

void MainWindow::grabButtonPressed()
{
    qDebug() << "Explicit grab";
    doGrab();
}

void MainWindow::grabButton2Pressed()
{
    qDebug() << "Delayed grab";
    QTimer::singleShot(2000, this, SLOT(doGrab()));
}

void MainWindow::doGrab()
{
    // Grab mouse for grab button
    if (!isCurrentlyGrabbing) {
        isCurrentlyGrabbing = true;
        qDebug() << "Grab pressed - Begin Grabbing";
        ui->grabButton->grabMouse();
        ui->grabButton->setText("Release Grab");
    } else {
        isCurrentlyGrabbing = false;
        qDebug() << "Grab pressed - Stop Grabbing";
        ui->grabButton->releaseMouse();
        ui->grabButton->setText("Explicit Grab");
    }
}

void MainWindow::modalButtonPressed()
{
    // Launch modal dialog
    QMessageBox msgBox;
    msgBox.setText("Just a normal modal messagebox.");
    msgBox.exec();
}
