
#include <HDB.h>

#include <QtGui>

#include "MainWindow.h"
#include "MdiChild.h"

int MainWindow::m_viewCounter = 0;

MainWindow::MainWindow()
{
    mdiArea = new QMdiArea;
    //mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    //mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    mdiArea->setViewMode(QMdiArea::TabbedView);
    setCentralWidget(mdiArea);
    
    newAct = new QAction(QIcon(":/images/new.png"), tr("&New 3D View"), this);
    newAct->setShortcuts(QKeySequence::New);
    connect(newAct, SIGNAL(triggered()), this, SLOT(new3DView()));
    
    fileMenu = menuBar()->addMenu(tr("&New 3D View"));
    fileMenu->addAction(newAct);

    //mdiArea->setBackground((NULL));
    //mdiArea->setUpdatesEnabled(false);
    mdiArea->setAutoFillBackground (false);
    mdiArea->setAttribute(Qt::WA_NoSystemBackground);
    mdiArea->setAttribute(Qt::WA_PaintOnScreen);
    mdiArea->setAttribute(Qt::WA_OpaquePaintEvent);
    setAutoFillBackground (false);

    setAttribute(Qt::WA_NoSystemBackground);
    setAttribute(Qt::WA_PaintOnScreen);

}

void MainWindow::closeEvent(QCloseEvent *event)
{
    mdiArea->closeAllSubWindows();
    if (mdiArea->currentSubWindow()) {
        event->ignore();
    } else {
        event->accept();
    }
}

void MainWindow::new3DView()
{
    MdiChild *child = createMdiChild();
    child->show();
    
    const char * driverType   = HDB::GetDriverType();
    const char * instanceName = HDB::GetInstanceBase();
    
    QString viewSegment = "/driver/" + QString(driverType) + "/" + QString(instanceName) + "+" + QString::number(m_viewCounter++);
    QString driverOptions;
    driverOptions.sprintf("double-buffering=on, disable input, use window ID = %d", (size_t)(child->winId()));
    
    qDebug("%s", viewSegment.toAscii().constData());
    qDebug("%s", driverOptions.toAscii().constData());
    
    HC_KEY viewKey = HC_KOpen_Segment(viewSegment.toAscii().constData());
        HC_Set_Driver_Options(driverOptions.toAscii().constData());
        HC_Set_Visibility("everything=on");
        HC_Set_Color("window=white");
        HC_Read_Metafile("model.hmf",".","restore state");
    HC_Close_Segment();
    
    child->setViewKey(viewKey);
    //child->setWindowPath(viewSegment.toAscii().constData());
}

MdiChild *MainWindow::createMdiChild()
{
    MdiChild *child = new MdiChild;
    mdiArea->addSubWindow(child);
    return child;
}
