#include <iostream>
#include <QApplication>
#include <QtCore>
#include "testTbw.h"

using std::cout;

MyMainWindow::MyMainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *centralWidget = new QWidget();
    setCentralWidget(centralWidget);
    table = new QTableWidget;
    addTimer = new QTimer;
    delTimer = new QTimer;
    btnRemove = new QPushButton("&Remove");
    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(table);
    layout->addWidget(btnRemove);
    centralWidget->setLayout(layout);
    connect(btnRemove, SIGNAL(clicked()), this, SLOT(removeRows()));
    connect(addTimer, SIGNAL(timeout()), this, SLOT(insertRows()));
    connect(delTimer, SIGNAL(timeout()), this, SLOT(removeRows()));
    this->resize(300,300);
    setupTable();
    //addTimer->start(1000);
    //delTimer->start(1100);
}

void MyMainWindow::insertRows(void){
    cout << "insertRows" << "\n";
    QAbstractItemModel *model = table->model();
    table->setSortingEnabled(false);
    model->insertRows(0,3);
    for(int r=0; r < 3; ++r){
        for(int c=0; c < 6; ++c){
            QString s = QString(tr("%1-%2").arg(r, c));
            QModelIndex idx = model->index(r, c, QModelIndex());
            model->setData(idx, QVariant(s), Qt::DisplayRole);
        }
        //Fill col 7 with a long string
        QString longString = genLongString();
        QModelIndex idxx = model->index(r, 6);
        model->setData(idxx, QVariant(longString), Qt::DisplayRole); 
    }
    table->setSortingEnabled(true);
    table->resizeColumnsToContents();
    table->sortByColumn(6);
  
}

void MyMainWindow::removeRows(void){
    cout << "removeRows" << "\n";
    int row = table->currentRow();
    if(row == -1){
        cout << "Please click any cell." << "\n";
    }
    cout << "Remove row:" << row << "\n";
    table->removeRow(row);
}

QString MyMainWindow::genLongString(void){
    srand((unsigned)time(NULL));
    char ch[129] = {0};
    for(int i=0; i<=128; ++i){
        int x = rand() % (sizeof(CCH) - 1);
        ch[i] = CCH[x];
    }
    QString s = QString((const char*)ch);
    return s;
}

void MyMainWindow::setupTable(){
    table->setColumnCount(7);
    table->hideColumn(5);
    table->sortByColumn(6);
    table->resizeColumnsToContents();
    table->resizeRowsToContents();
}

int main(int argc, char *argv[]){

    QApplication app(argc, argv);
    MyMainWindow mw;
    mw.addTimer->start(10*100);
    mw.delTimer->start(11*100);
    mw.show();
    return app.exec();

}
