mainwindow.cpp 5.9 KB
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <iostream>
#include "customsqlmodel.h"
#include <QSqlQuery>
#include <sstream>
#include <fstream>

const char* MainWindow::CONFIG_PATH = "/usr/local/etc/apunts.conf";

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    std::string* parameters = loadConfig(CONFIG_PATH);
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(parameters[0].c_str());
    db.setUserName(parameters[1].c_str());
    db.setPassword(parameters[2].c_str());
    db.setDatabaseName(parameters[3].c_str());
    if(!db.open())
    {
        QMessageBox::critical(this,"Error",trUtf8("No s'ha pogut obrir la base de dades"));
        exit(-1);
    }
    delete[] parameters;
    connect(ui->exitButton,SIGNAL(clicked()),this, SLOT(close()));
    connect(ui->addButton,SIGNAL(clicked()),this,SLOT(showAddDialog()));
    connect(ui->editButton,SIGNAL(clicked()),this,SLOT(showEditDialog()));
    connect(ui->deleteButton,SIGNAL(clicked()),this,SLOT(deleteReserva()));
    connect(ui->tableView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(showEditDialog()));
    connect(ui->tableView->horizontalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(sort(int)));
    query = "SELECT r.nom_i_cognoms as \"Nom i cognoms\", a.nom as Apunts, r.telefon as Telèfon, r.data as Data, r.comentari as Comentari FROM assignatures as a, reserves as r WHERE a.num = r.apunts ";
    orderQuery= ";";
    triggerUpdate();
    ui->tableView->setModel(&tableViewModel);
    ui->tableView->resizeColumnsToContents();
    ui->tableView->resizeRowsToContents();
    setStatusMessage(trUtf8("Llistat de préstecs carregat"));
}

void MainWindow::triggerUpdate()
{

    std::string str = query+orderQuery;
    tableViewModel.setQuery(trUtf8(str.c_str()));
    ui->tableView->resizeRowsToContents();
}

void MainWindow::setStatusMessage(const QString &str)
{
    ui->statusBar->showMessage(str);
}

QSqlRecord& MainWindow::getSelectedReserva()
{
    return selectedReserva;
}

int MainWindow::getNum(QString name)
{
    QSqlQuery number;
    number.prepare("SELECT num FROM assignatures WHERE nom = :n");
    number.bindValue(":n",name);
    number.exec();
    number.next();
    return number.record().value(0).toInt();
}

std::string* MainWindow::loadConfig(const char *path)
{
    std::ifstream conf;
    conf.open(path);
    if(!conf.is_open())
    {
        conf.close();
        QMessageBox::critical(this,"Error",trUtf8("No s'ha pogut carregar el fitxer de configuració. Aviseu a l'administrador."));
        exit(-2);
    }
    std::string host, user, pass, db;
    std::getline(conf,host);
    std::getline(conf,user);
    std::getline(conf,pass);
    std::getline(conf,db);
    host = host.substr(5);
    user = user.substr(5);
    pass = pass.substr(9);
    db = db.substr(9);
    std::string* ret = new std::string[4];
    ret[0] = host;
    ret[1] = user;
    ret[2] = pass;
    ret[3] = db;
    return ret;
}

bool MainWindow::checkPhone(QString phone)
{
    bool isNumber;
    phone.toInt(&isNumber);
    if((!isNumber) || (phone.length() != 9))
    {
        return false;
    }
    return true;
}

void MainWindow::showAddDialog()
{
    add = new AddDialog(this);
    add->show();
}

void MainWindow::showEditDialog()
{
    if(ui->tableView->selectionModel()->selectedIndexes().isEmpty())
    {
        QMessageBox::critical(this,"Error",trUtf8("No s'ha seleccionat cap préstec"));
        return;
    }
    QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
    if(indexes.count() > 1)
    {
        QMessageBox::critical(this,"Error",trUtf8("Només es pot editar una entrada a la vegada"));
        return;
    }
    selectedReserva=tableViewModel.record((indexes.at(0).row()));
    edit = new EditDialog(this);
    edit->show();
}

void MainWindow::deleteReserva()
{
    QSqlQuery deleteQuery, assignaturaQuery;
    QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
    if(!warnUser(indexes.count()))
    {
        return;
    }
    for(int i = 0; i < indexes.count(); i++)
    {
        int number = getNum(tableViewModel.record(indexes.at(i).row()).value(1).toString());
        deleteQuery.prepare("DELETE FROM reserves WHERE apunts = :n");
        deleteQuery.bindValue(":n",number);
        deleteQuery.exec();
        assignaturaQuery.prepare("UPDATE assignatures SET agafats = '0' WHERE num = :n;");
        assignaturaQuery.bindValue(":n",number);
        assignaturaQuery.exec();
    }
    triggerUpdate();
    if(deleteQuery.isActive() && assignaturaQuery.isActive())
    {
        setStatusMessage(trUtf8("Canvis desats: s'ha eliminat el préstec"));
        return;
    }
    setStatusMessage(trUtf8("Error: no s'ha pogut escriure a la base de dades"));
}

void MainWindow::dismissAddDialog()
{
    add->close();
    delete add;
    add = 0;
}

void MainWindow::dismissEditDialog()
{
    edit->close();
    delete edit;
    edit = 0;
}

bool MainWindow::warnUser(int elements)
{
    if(elements)
    {
        std::stringstream sstream;
        sstream << "Segur que vols eliminar ";
        sstream << elements;
        sstream << " préstecs?";
        int n = QMessageBox::warning(this,trUtf8("Eliminar préstec?"),trUtf8(sstream.str().c_str()),"&Si","&No",QString::null,1,1);
        if(!n)
        {
            return true;
        }
        return false;
    }
    else
    {
        QMessageBox::critical(this,"Error",trUtf8("No s'ha seleccionat cap préstec"));
        return false;
    }
}

void MainWindow::sort(int index)
{
    orderQuery = "ORDER BY ";
    std::stringstream sstream;
    sstream << (index+1);
    orderQuery.append(sstream.str());
    Qt::SortOrder sortOrder = ui->tableView->horizontalHeader()->sortIndicatorOrder();
    if(sortOrder == Qt::AscendingOrder)
    {
        orderQuery += " ASC;";
    }
    else
    {
        orderQuery += " DESC;";
    }
    triggerUpdate();
}

MainWindow::~MainWindow()
{
    delete ui;
}