void FormGestioneFerie::on_cbMatricola_currentIndexChanged(const QString &arg1)
{

    ui->cbCognome->setCurrentIndex(ui->cbMatricola->currentIndex());
    QSqlQuery query1(QString("SELECT nome FROM anagrafica where Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    query1.next();
    ui->lNome->setText( query1.value(0).toString() );

    QSqlTableModel *model = new QSqlTableModel(this, this->db);
    model->setTable("assenze");
    model->setEditStrategy(QSqlTableModel::OnFieldChange);
    model->select();
    model->setFilter(QString("Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));

    model->sort(2,Qt::AscendingOrder);
      model->setHeaderData(1, Qt::Horizontal, tr("MATRICOLA"));
      model->setHeaderData(2, Qt::Horizontal, tr("DATA"));
      model->setHeaderData(3, Qt::Horizontal, tr("CAUSA"));
      ui->tvPermessi->setModel(model);
      ui->tvPermessi->hideColumn(0);
      ui->tvPermessi->resizeColumnsToContents();
      ui->tvPermessi->resizeRowsToContents();
      ui->tvPermessi->selectRow(0);

}
void FormGestioneFerie::on_pbAggiungiPermesso_clicked()
{
    for(QDate a=ui->dePermessiDal->date(); a.operator <=( ui->dePermessiAl->date());a= a.addDays(1) )
   {

    qDebug() << "Permesso per "+ui->cbMatricola->currentText()+" per il giorno "+a.toString("dd/MM/yyyy");


    QSqlQuery query;
    query.prepare("INSERT INTO assenze (ID, matricola, causa, data)" "VALUES (?, ?, ?, ?)");
   // query.addBindValue( ui->cbMatricola->currentText()+"_"+ui->dePermessiDal->date().toString("dd/MM/yyyy"));
    query.addBindValue( ui->cbMatricola->currentText()+"_"+a.toString("dd/MM/yyyy"));
    query.addBindValue( ui->cbMatricola->currentText());
    query.addBindValue( ui->cbTipoPermesso->currentText());
   // query.addBindValue( ui->dePermessiDal->date().toString("dd/MM/yyyy"));
    query.addBindValue( a.toString("dd/MM/yyyy"));
    if(query.exec())
    {
        QMessageBox msgBox;
        msgBox.setText("Inserzione nel database.");
        msgBox.setInformativeText(QString("Permesso per il giorno %1 inserito correttamente.").arg(a.toString("dd/MM/yyyy")));
        msgBox.setStandardButtons(QMessageBox::Ok );
        msgBox.setIcon(QMessageBox::Information);
        msgBox.exec();
    }
    else
    {
        QMessageBox msgBox;
        msgBox.setText("Inserzione nel database.");
        msgBox.setInformativeText(QString("Permesso per il giorno %1 NON inserito nel database. Probabilmente è gia stato inserito un permesso per lo stesso giorno.").arg(a.toString("dd/MM/yyyy")));
        msgBox.setStandardButtons(QMessageBox::Ok );
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();
    }

    QSqlTableModel *model = new QSqlTableModel(this, this->db);
    model->setTable("assenze");
    model->setEditStrategy(QSqlTableModel::OnFieldChange);
    model->select();
    model->setFilter(QString("Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));

    model->sort(2,Qt::AscendingOrder);
      model->setHeaderData(1, Qt::Horizontal, tr("MATRICOLA"));
      model->setHeaderData(2, Qt::Horizontal, tr("DATA"));
      model->setHeaderData(3, Qt::Horizontal, tr("CAUSA"));
      ui->tvPermessi->setModel(model);
      ui->tvPermessi->hideColumn(0);
      ui->tvPermessi->resizeColumnsToContents();
      ui->tvPermessi->resizeRowsToContents();
      ui->tvPermessi->selectRow(0);

  }
}
FormGestioneFerie::FormGestioneFerie(QSqlDatabase db, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormGestioneFerie)
{
    ui->setupUi(this);

    QDate oggi;
    ui->dePermessiDal->setDate(oggi.currentDate());
    ui->dePermessiAl->setDate(oggi.currentDate());

    this->db= db;



    QSqlQuery query(QString("SELECT Matricola,cognome FROM anagrafica"));
    while (query.next())
    {
     ui->cbMatricola->addItem(  query.value(0).toString() );
     ui->cbCognome->addItem(  query.value(1).toString() );
     ui->lNome->setText( query.value(2).toString() );
    }
    QSqlQuery query1(QString("SELECT nome FROM anagrafica where Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    query1.next();
    ui->lNome->setText( query1.value(0).toString() );



    QSqlTableModel *model = new QSqlTableModel(this, this->db);
    model->setTable("assenze");
    model->setEditStrategy(QSqlTableModel::OnFieldChange);
    model->select();
    model->setFilter(QString("Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    model->sort(2,Qt::AscendingOrder);
    model->setHeaderData(1, Qt::Horizontal, tr("MATRICOLA"));
    model->setHeaderData(2, Qt::Horizontal, tr("DATA"));
    model->setHeaderData(3, Qt::Horizontal, tr("CAUSA"));
    ui->tvPermessi->setModel(model);
    ui->tvPermessi->hideColumn(0);
    ui->tvPermessi->resizeColumnsToContents();
    ui->tvPermessi->resizeRowsToContents();
    ui->tvPermessi->selectRow(0);


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

    QString data_path = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
    QDir data_dir;
    data_dir.mkpath(data_path);
    QString db_path = data_path + QDir::separator() + QString("assets.db");
    qDebug() << "DB path : " << db_path;

    db_helper = new DBHelper(db_path);
    QSqlError err = db_helper->initDb();
    if (err.type() != QSqlError::NoError) {
        showError(err);
        throw err;
    }

    market = new CryptocoinChartsMDP();
    updateCurrencies();

    model = new QSqlRelationalTableModel(ui->assetsTable);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setTable("assets");

    currency_column_index = model->fieldIndex("currency_id");
    quantity_index = model->fieldIndex("quantity");
    price_btc_index = model->fieldIndex("price_btc");
    mv_btc_index = model->fieldIndex("market_value_btc");
    price_usd_index = model->fieldIndex("price_usd");
    mv_usd_index = model->fieldIndex("market_value_usd");

    model->setRelation(currency_column_index, QSqlRelation("currencies", "id", "code"));

    model->setHeaderData(currency_column_index, Qt::Horizontal, tr("Currency"));
    model->setHeaderData(model->fieldIndex("quantity"), Qt::Horizontal, tr("Quantity"));
    model->setHeaderData(model->fieldIndex("price_btc"), Qt::Horizontal, tr("Price (BTC)"));
    model->setHeaderData(model->fieldIndex("market_value_btc"), Qt::Horizontal, tr("Market Value (BTC)"));
    model->setHeaderData(model->fieldIndex("price_usd"), Qt::Horizontal, tr("Price (USD)"));
    model->setHeaderData(model->fieldIndex("market_value_usd"), Qt::Horizontal, tr("Market Value (USD)"));

    if (!model->select()) {
        showError(model->lastError());
        return;
    }

    ui->assetsTable->setModel(model);
    ui->assetsTable->setItemDelegate(new QSqlRelationalDelegate(ui->assetsTable));
    ui->assetsTable->setColumnHidden(model->fieldIndex("id"), true);
    ui->assetsTable->setSelectionBehavior(QAbstractItemView::SelectRows);

    mapper = new QDataWidgetMapper(this);
    mapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
    AssetEditDelegate *delegate = new AssetEditDelegate(this);
    mapper->setItemDelegate(delegate);
    mapper->setModel(model);
    mapper->addMapping(ui->quantityEdit, model->fieldIndex("quantity"));

    QSqlTableModel *relationModel = model->relationModel(currency_column_index);
    relationModel->sort(relationModel->fieldIndex("code"), Qt::AscendingOrder);
    ui->currencyComboBox->setModel(relationModel);
    ui->currencyComboBox->setModelColumn(relationModel->fieldIndex("code"));
    ui->currencyComboBox->installEventFilter(delegate);
    mapper->addMapping(ui->currencyComboBox, currency_column_index);

    connect(ui->assetsTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            mapper, SLOT(setCurrentModelIndex(QModelIndex)));

    connect(delegate, SIGNAL(dataChanged (const QModelIndex&)), this, SLOT(data_changed(QModelIndex)));

    ui->assetsTable->setCurrentIndex(model->index(0, 0));

    refreshMarketData(false);

    for (int c = 0; c < ui->assetsTable->horizontalHeader()->count(); ++c)
        ui->assetsTable->horizontalHeader()->setSectionResizeMode(c, QHeaderView::Stretch);

}
void FormGestioneFerie::on_tvPermessi_doubleClicked(const QModelIndex &index)
{

    if(index.column()==2)
    {
        QMessageBox msgBox;
        msgBox.setText("Cancella assenza programmata.");
        msgBox.setInformativeText(QString("Cancellare l'assenza programmata di %2 per il giorno %1 ?").arg(index.data().toString()).arg(ui->cbCognome->currentText()));
        msgBox.setStandardButtons(QMessageBox::Apply |QMessageBox::Discard  );
        msgBox.setIcon(QMessageBox::Question);
        int ret = msgBox.exec();
        if (ret==QMessageBox::Apply )
        {
            QSqlQuery query(QString("DELETE FROM assenze where id=\"%1\"").arg(ui->cbMatricola->currentText()+"_"+index.data().toString()));
            query.exec();
            qDebug() << query.lastError();

            QSqlTableModel *model = new QSqlTableModel(this, this->db);
            model->setTable("assenze");
            model->setEditStrategy(QSqlTableModel::OnFieldChange);
            model->select();
            model->setFilter(QString("Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));

            model->sort(2,Qt::AscendingOrder);
            model->setHeaderData(1, Qt::Horizontal, tr("MATRICOLA"));
            model->setHeaderData(2, Qt::Horizontal, tr("DATA"));
            model->setHeaderData(3, Qt::Horizontal, tr("CAUSA"));
            ui->tvPermessi->setModel(model);
            ui->tvPermessi->hideColumn(0);
            ui->tvPermessi->resizeColumnsToContents();
            ui->tvPermessi->resizeRowsToContents();
            ui->tvPermessi->selectRow(0);
        }
    }

}