#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlDatabase>
#include <QSqlError>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
   ui->setupUi(this);

   m_grid = new Grid();
   m_grid->setViewType(Grid::TableView);
   m_pGridView = m_grid->view<GridTableView>();
   m_pGridView->options().setFilterEnabled(true);

   ui->frm_grid->layout()->addWidget(m_grid);

   {
        QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QMYSQL"), QLatin1String("TestGrid8"));
        db.setHostName("xxx.xxx.xxx.xxx");
        db.setPort(3306);
        db.setDatabaseName("xxx");
        db.setUserName("xxx");
        db.setPassword("xxx");
        db.setConnectOptions();
        db.setConnectOptions("MYSQL_OPT_RECONNECT=1");
        bool bDbResult = db.open();
        if(!bDbResult)
            qDebug()<<db.lastError().text();
        else
        {            
            m_pModel = new QSqlQueryModel(this);
            m_pModel->setQuery("select * from mytable", db);
            m_pGridView->setModel(m_pModel);
        }
   }     

   connect(ui->btn_refresh, SIGNAL(clicked(bool)), this, SLOT(OnRefresh()));   
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::OnRefresh()
{
    //Save the filter state before refreshing.
    bool bFilterActive = m_pGridView->filter()->isActive();

    {
         QSqlDatabase db = QSqlDatabase::database("TestGrid8");
		 //NOTE: Now we refresh the model
         m_pModel->setQuery("select * from mytable", db);
         //NOTE: at this point any user-applied filter panel disappears, and all data is shown, unfiltered.
    }

    if(bFilterActive)
    {
        //NOTE: Uncommenting the below line makes the filter panel show again, and data is also correctly re-filtered, so that is our current workaround
        //m_pGridView->showFilterPanel();
    }
}

