#include "mainwindow.h"
#include <QTime>
#include <QFile>
#include <QMessageBox>
#include <QInputDialog>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    if (initDb() == false)
    {
        QMessageBox msg;
        msg.setText("Can't open database...");
        msg.exec();
        return;
    }
    setMenu();
    setDialog();
    setCentralWidget(&m_progress);
}

MainWindow::~MainWindow()
{
    if (m_db.isOpen() == false) return;
    QFile file("size.sts");
    if (!file.open(QIODevice::WriteOnly))
        return;
    int anData[(D_DIALOG_MAX+1)*4];
    for (int i = 0; i < D_DIALOG_MAX;i++)
    {
        anData[i*4+0] = m_pDialogs[i]->geometry().left();
        anData[i*4+1] = m_pDialogs[i]->geometry().top();
        anData[i*4+2] = m_pDialogs[i]->geometry().width();
        anData[i*4+3] = m_pDialogs[i]->geometry().height();
    }        
    anData[D_DIALOG_MAX*4+0] = geometry().left();
    anData[D_DIALOG_MAX*4+1] = geometry().top();
    anData[D_DIALOG_MAX*4+2] = geometry().width();
    anData[D_DIALOG_MAX*4+3] = geometry().height();
    file.write((char*)&anData,sizeof(int)*(D_DIALOG_MAX+1)*4);
    file.close();
    m_db.close();
}

bool MainWindow::initDb()
{
    m_db = QSqlDatabase::addDatabase("QMYSQL");
    m_db.setHostName("bigbird.iptime.org");
    m_db.setUserName("admin");
    m_db.setPassword("admin123");
    m_db.setDatabaseName("concepters");

    connect(&m_timerAlive, SIGNAL(timeout()), this, SLOT(Alive()));
    m_timerAlive.start(60*60000);
    return m_db.open();
}


void MainWindow::setMenu()
{
    {
        QMenu *pFile = menuBar()->addMenu("File");
        connect(pFile->addAction("New"), SIGNAL(triggered()), this, SLOT(FileNew()));
        connect(pFile->addAction("CSV Import"), SIGNAL(triggered()), this, SLOT(FileImport()));
        connect(pFile->addAction("CSV Export"), SIGNAL(triggered()), this, SLOT(FileExport()));
        pFile->addSeparator();
        connect(pFile->addAction("Exit"), SIGNAL(triggered()), this, SLOT(FileExit()));
    }
    {
        QMenu *pFile = menuBar()->addMenu("Window");
        connect(pFile->addAction("Load"), SIGNAL(triggered()), this, SLOT(WindowLoad()));
        connect(pFile->addAction("Data"), SIGNAL(triggered()), this, SLOT(WindowData()));
        connect(pFile->addAction("Filter Object"), SIGNAL(triggered()), this, SLOT(WindowFilterObject()));
        connect(pFile->addAction("Filter"), SIGNAL(triggered()), this, SLOT(WindowFilter()));
        connect(pFile->addAction("Count"), SIGNAL(triggered()), this, SLOT(WindowCount()));
    }
}

void MainWindow::setDialog()
{
    m_pBatchRunDlg = new SBatchRun;
    m_pDataDlg = new SDataDlg;
    m_ploadDlg = new SLoadDlg;
    m_pCountDlg = new SCountDlg;
    m_pFilterObjectDlg = new SFilterObject;
    m_pFilterDlg = new SFilterDlg;
    m_pDialogs[0] = m_pDataDlg;
    m_pDialogs[1] = m_ploadDlg;
    m_pDialogs[2] = m_pCountDlg;
    m_pDialogs[3] = m_pFilterObjectDlg;
    m_pDialogs[4] = m_pFilterDlg;
    //m_pDialogs[5] = m_pBatchRunDlg;
    QFile file("size.sts");
    if (file.open(QIODevice::ReadOnly))
    {
        int anData[D_DIALOG_MAX*4] = {0,};
        file.read((char*)&anData[0],D_DIALOG_MAX*4*sizeof(int));
        for (int i = 0; i < D_DIALOG_MAX;i++)
        {
            if (anData[i*4+2] != 0)
                m_pDialogs[i]->setGeometry(anData[i*4+0],anData[i*4+1],anData[i*4+2],anData[i*4+3]);
        }
        file.seek(D_DIALOG_MAX*4*sizeof(int));
        if (file.read((char*)&anData[0],4*sizeof(int)) > 0 )
            setGeometry(anData[0],anData[1],anData[2],anData[3]);
        file.close();
    }
    for (int i = 0; i < D_DIALOG_MAX;i++)
        m_pDialogs[i]->show();
}

void MainWindow::InsertLog(QString str)
{
    /*
    QTime time = QTime::currentTime();
    QString strOut = time.toString("[hh:mm:ss] ") + str;
    m_pLog->addItem(strOut);
    if (m_pLog->count() > 1024)
    {
        m_pLog->removeItemWidget(m_pLog->item(0));
        QListWidgetItem* item = m_pLog->takeItem(0);
        delete item;
    }
    m_pLog->setCurrentRow( m_pLog->count() - 1 );
    m_pLog->repaint();
    */
}


void MainWindow::FileNew()
{
    bool ok;
    QString text = QInputDialog::getText(this,"New Row Count","Count :", QLineEdit::Normal,"0", &ok);
    if (ok)
    {
        STable *pTable = (STable *)m_pDataDlg->AddTable("<New>");
        QVector <QStringList> column = GetColumn().data();
        pTable->SetHeaderList(&column,SColumn::E_NAME);
        pTable->setRowCount(text.toInt());
        for(int i = 0; i < text.toInt(); i++)
        {
            for(int j = 0; j < column.size(); j++)
            {
                pTable->setItem(i, j, new QTableWidgetItem(QString("  ")));
            }
        }
    }
}

void MainWindow::FileImport()
{
    QString strFilename = QFileDialog::getOpenFileName(0,"Import file",QDir::currentPath(),
            "csv files (*.csv);;All files (*.*)",new QString("Text files (*.csv)"));

    QFile file(strFilename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;

    QVector <QByteArray> vecByte;
    bool bQuit = true;
    while(bQuit)
    {
        QByteArray byte = file.readLine();
        if (byte.isEmpty()) { bQuit = false; continue; }
        vecByte.push_back(byte);
    }
    file.close();
    m_pDataDlg->Import(vecByte);
}

void MainWindow::FileExport()
{
    QString strFilename = QFileDialog::getSaveFileName(0,"Exoprt file",QDir::currentPath(),"csv files (*.csv);;All files (*.*)",new QString("Text files (*.csv)"));
    if (strFilename.toLower().right(4) != QString(".csv"))
        strFilename += ".csv";

    m_pDataDlg->Export(strFilename);
}

void MainWindow::FileExit()
{
    for (int i = 0; i < D_DIALOG_MAX;i++)
        m_pDialogs[i]->close();
    m_graph.close();
    close();
}

void MainWindow::WindowLoad()
{
    if (m_ploadDlg->isHidden())
        m_ploadDlg->show();
    else
        m_ploadDlg->hide();
}

void MainWindow::WindowFilterObject()
{
    if(m_pFilterObjectDlg->isHidden())
        m_pFilterObjectDlg->show();
    else
        m_pFilterObjectDlg->hide();
}

void MainWindow::WindowCount()
{
    if (m_pCountDlg->isHidden())
        m_pCountDlg->show();
    else
        m_pCountDlg->hide();
}

void MainWindow::WindowFilter()
{
    if (m_pFilterDlg->isHidden())
        m_pFilterDlg->show();
    else
        m_pFilterDlg->hide();
}

void MainWindow::WindowData()
{
    if (m_pDataDlg->isHidden())
        m_pDataDlg->show();
    else
        m_pDataDlg->hide();
}

void MainWindow::closeEvent(QCloseEvent * event)
{
    Q_UNUSED(event);
    FileExit();
}

void MainWindow::Alive()
{
    QSqlQuery query;
    query.exec("SELECT 1");
    query.next();
}
