#include "abstractwizard.h"

AbstractWizard::AbstractWizard(const QString &appDir, const QString &workspaceWizardLocation, QSettings *vagoSettings, const bool hasRestartButton)
{
    this->appDir = appDir;
    this->workspaceWizardLocation=workspaceWizardLocation;
    this->vagoSettings=vagoSettings;
    this->hasRestartButton = hasRestartButton;
    this->myWizard.setWindowFlags(Qt::Window); // add minimize button in QWizard
}

void AbstractWizard::showWizard(const QString &windowsTitle, const QString &windowsIcon){
    // Connect finished signal to our function
    QObject::connect(&myWizard, SIGNAL(finished(int)), this, SLOT(wizardFinished(int)));

    // If it has a restart button setup it
    if(this->hasRestartButton){
        QPushButton *restartButton = new QPushButton("Restart");
        this->myWizard.setButton(QWizard::CustomButton1,restartButton);
        this->myWizard.setOption(QWizard::HaveCustomButton1, true);

        connect(&this->myWizard, SIGNAL(currentIdChanged(int)), this, SLOT(pageChanged(int)));
        connect(restartButton, SIGNAL(clicked(bool)), this, SLOT(restartWizard()));
    }

    myWizard.setWindowIcon(QIcon(windowsIcon));
    myWizard.setWindowTitle(windowsTitle);

    //Center and resize QWizard (http://www.thedazzlersinc.com/source/2012/06/04/qt-center-window-in-screen/)
#ifdef Q_OS_WIN
    myWizard.resize(640,480);
#else
    myWizard.resize(800,600); // Mac OS pcs should be able to render this resolution without any problem. It's also better
    // because the components on mac use more space
#endif
    QRect position = myWizard.frameGeometry();
    position.moveCenter(QDesktopWidget().availableGeometry().center());
    myWizard.move(position.topLeft());
    //

    // Show non modal window
    myWizard.show();
}

QWizardPage* AbstractWizard::createIntroPage(const QString &text) {
    QWizardPage *page = new QWizardPage;
    page->setTitle("Introduction");

    QLabel *label = new QLabel(text);
    label->setWordWrap(true);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(label);
    page->setLayout(layout);

    return page;
}

void AbstractWizard::wizardFinished(int resultStatus){
    beforeClose(static_cast<QDialog::DialogCode>(resultStatus));

    // delete itself
    delete this;
}

void AbstractWizard::restartWizard(){
    this->myWizard.restart();
}

void AbstractWizard::pageChanged(int pageId){
    // Last page?
    if(pageId==this->myWizard.pageIds().size()-1){
        this->myWizard.setOption(QWizard::HaveCustomButton1, true); // set visible
        this->myWizard.button(QWizard::BackButton)->setEnabled(false); // disable back button, use restart if needed
        return;
    }
    this->myWizard.setOption(QWizard::HaveCustomButton1, false); // set invisible
    this->myWizard.button(QWizard::BackButton)->setEnabled(true); // set enable back button
}
