#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "qgftfptargetsim.h"

#include "qggrifobeamupform.h"
#include "beamupfilemonitor.h"

#include "sitesimdialog.h"

#include <QSettings>
#include <QHostInfo>
#include <QMessageBox>
#include <QTimer>
#include <QCloseEvent>

static QgGrifoBeamUpForm* bForm;
static BeamupFileMonitor* fMon;

//#define SIMULATION

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

    QCoreApplication::setOrganizationName("Leonardo");
    QCoreApplication::setOrganizationDomain("Leonardo.com");
    QCoreApplication::setApplicationName("GrifoBeamUp");

    //ui->plainTextEdit->setVisible(false);
    bForm=new QgGrifoBeamUpForm;
    ui->verticalLayout->addWidget(bForm);

    QHostInfo hi=QHostInfo::fromName(QHostInfo::localHostName());
    setWindowTitle(QString("Host: %1").arg(hi.hostName()));

    ui->mainToolBar->setVisible(false);
    ui->statusBar->setEnabled(false);
    ui->statusBar->setVisible(false);
    QTimer::singleShot(100, this, SLOT(postInit()));

    fMon=new BeamupFileMonitor(this);
}

MainWindow::~MainWindow()
{
    fMon->cleanUp();
    delete ui;
}

#include "qggrifobeamupproperties.h"

void MainWindow::postInit()
{
#ifdef SIMULATION
    if (bForm->props.property("simulator").toBool())
    {
        SiteSimDialog* z0=new SiteSimDialog(this);
        z0->show();
        SiteSimDialog* z1=new SiteSimDialog(this);
        z1->show();
        SiteSimDialog* d0=new SiteSimDialog(this);
        d0->show();
        SiteSimDialog* d1=new SiteSimDialog(this);
        d1->show();
        SiteSimDialog* d2=new SiteSimDialog(this);
        d2->show();
        SiteSimDialog* d3=new SiteSimDialog(this);
        d3->show();

        z0->initialize("ZynQ", 0, 50069);
        z1->initialize("ZynQ", 1, 50070);

        d0->initialize("DSP", 2, 50071);
        d1->initialize("DSP", 2, 50072);
        d2->initialize("DSP", 2, 50073);
        d3->initialize("DSP", 2, 50074);
    }
#endif
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    int r=QMessageBox::question(this, QString(), "Quit?",
                                "Yes", "Also save settings", "No");
    if (r<2)
    {
        if (r==1)
            bForm->saveSettings();

        fMon=0;
        event->accept();
    }
    else
        event->ignore();
}


//static void enum_drive();

bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    if (fMon)
        fMon->nativeEventDriveDetection(eventType, message, result);
    return false;
}

