#include "qgscopemainwindow.h"
#include "ui_qgscopemainwindow.h"

#include <QTimer>
#include <QDebug>
#include <QSettings>
#include <QCloseEvent>
#include <QComboBox>
#include <QMessageBox>
#include <QLabel>

#include "qgscopechrono.h"
#include "qglogger.h"
#include "qgapplicationperformance.h"

#include "qgscopeworkbench.h"

#include <DockManager.h>

static void (*iHandler)();

class QgScopeMainWindow::Implementation
{
public:
    QComboBox* cmChrono;

    QLabel* lblPeformance;

};

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

    p_.lblPeformance=new QLabel;

    ui->statusbar->addPermanentWidget(p_.lblPeformance);

    p_.cmChrono=new QComboBox;

    p_.cmChrono->addItem("x0", 0);
    p_.cmChrono->addItem("x1", 1);
    p_.cmChrono->addItem("x2", 2);
    p_.cmChrono->addItem("x5", 5);
    p_.cmChrono->addItem("x10", 10);

    p_.cmChrono->addItem("(?)", -1);

    connect(p_.cmChrono, static_cast<void (QComboBox::*)(int index)>(&QComboBox::currentIndexChanged), this,
            [this](int /*index*/)
            {
                int v=p_.cmChrono->currentData().toInt();
                if (v>=0)
                    QgScopeChrono::instance().setMultiplier(v);
            }
            );
    connect(&QgScopeChrono::instance(), &QgScopeChrono::chronoMultiplierChanged, this,
            [this](unsigned int m)
            {
                int index=p_.cmChrono->findData(m);
                if (index>-1)
                {
                    p_.cmChrono->setCurrentIndex(index);
                }
                else
                {
                    index=p_.cmChrono->findData(-1);
                    if (index>=0)
                    {
                      p_.cmChrono->setItemText(index, QString("x%1").arg(m));
                    }
                }
            }
            );

    connect(&QgApplicationPerformance::instance(), QgApplicationPerformance::countersUpdated, this,
            [this]()
    {
        p_.lblPeformance->setText(QgApplicationPerformance::instance().toString());
    });

    QTimer::singleShot(10, this, SLOT(postInit()));
}

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


QComboBox* QgScopeMainWindow::chronoCB() const
{
    return p_.cmChrono;
}

void QgScopeMainWindow::postInit()
{
    //qDebug()<<"ScopeMainWindow: invoking initializer";
    if (iHandler)
        iHandler();


}

void QgScopeMainWindow::setClientInitializer(void (*handler)())
{
    iHandler=handler;
}

QString QgScopeMainWindow::restoreLayout(const QString &lyname)
{
    //LV legge dal file di configurazione le impostazioni del layout della schermata di lavoro
    //per cercare di riaprire la situazione come era stata chiusa precedentemente.
    QSettings settings("wb.ini", QSettings::IniFormat);

     settings.beginGroup("MainWindow");
     restoreGeometry(settings.value("windowGeometry").toByteArray());
     restoreState(settings.value("windowState").toByteArray());
     //restoreDockWidget();
     //QgScopeWorkbench::instance().dockManager()->restoreState(settings.value("qtads").toByteArray());
     settings.endGroup();

     if (!QgScopeWorkbench::instance().dockManager()->perspectiveNames().contains("default"))
        QgScopeWorkbench::instance().dockManager()->addPerspective("default");

     QSettings sads("wb-ads.ini", QSettings::IniFormat);
     QString last=sads.value("myads/lastPerspective", "default").toString();
     if (!lyname.isEmpty())
         last=lyname;
     QgScopeWorkbench::instance().dockManager()->loadPerspectives(sads);
     QgScopeWorkbench::instance().dockManager()->openPerspective(last); //"default");
     return last;
}

void QgScopeMainWindow::closeEvent(QCloseEvent* evn)
{
    QMessageBox::StandardButton reply=QMessageBox::question(this, "QgScope", "Quit?");
    if (reply!=QMessageBox::Yes)
    {
        evn->ignore();
        return;
    }

    //LV salva il layout attuale per una successiva riapertura con le schermate nella stessa posizione.
    QSettings settings("wb.ini", QSettings::IniFormat);

    settings.beginGroup("MainWindow");

    settings.setValue("windowGeometry", saveGeometry());
    settings.setValue("windowState", saveState());

    settings.setValue("qtads", QgScopeWorkbench::instance().dockManager()->saveState());
    settings.endGroup();

    //QgScopeWorkbench::instance().dockManager()->addPerspective("default");
    //if (!QgScopeWorkbench::instance().dockManager()->perspectiveNames().contains("default"))
    //   QgScopeWorkbench::instance().dockManager()->addPerspective("default");
    QgScopeWorkbench& wb=QgScopeWorkbench::instance();

    QSettings sads("wb-ads.ini", QSettings::IniFormat);
    sads.setValue("myads/lastPerspective", wb.defaultPerspectiveName());
    wb.dockManager()->savePerspectives(sads);

    QgLogger::logStop();

    auto wl=children();
    for(auto w: wl)
    {
        QMainWindow* m=qobject_cast<QMainWindow*>(w);
        if (m)
            m->close();
    }

    evn->accept();
}
