#include "requetes.h"
#include "edit.h"

#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>
#include <QFile>
#include <QMessageBox>

Requete::Requete(QObject * parent)
{
    setupUi(this);
    initialise();
    initItemsCombo(0);
    fillComboConditions();
    connect(quitButton,SIGNAL(pressed()),this,SLOT(close()));    
    connect(tablesComboBox,SIGNAL(activated(int)),this,SLOT(initItemsCombo(int)));
    connect(itemsComboBox,SIGNAL(activated(int)),this,SLOT(writeInSelectEdit(int)));
    connect(applyButton,SIGNAL(pressed()),this,SLOT(writeAllSelectSentence()));
    connect(searchButton,SIGNAL(pressed()),this,SLOT(search()));
}

Requete::~Requete(){}

void Requete::initialise()
{
    m_db = QSqlDatabase::database("DrTuxTest");
    initTablesCombo();
}

void Requete::initTablesCombo()
{
    QSqlQuery qy(m_db);
    QString req = QString("SHOW %1 FROM %2").arg("tables","DrTuxTest");
    QStringList listOfTables;
    if (!qy.exec(req))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
        }
    while (qy.next())
    {
          QString r = qy.value(0).toString();
          listOfTables << r;
        }
    tablesComboBox->addItems(listOfTables);
}

void Requete::initItemsCombo(int tableIndex)
{
    itemsComboBox->clear();
    fieldsComboBox->clear();
    QString table = tablesComboBox->currentText();
    QSqlQuery qy(m_db);
    QString req = QString("SHOW COLUMNS FROM %1").arg(table);
    if (!qy.exec(req))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
        }
    while (qy.next())
    {
        QString field = qy.value(0).toString();
        itemsComboBox->addItem(field);
        fieldsComboBox->addItem(field);
        }
}

void Requete::writeInSelectEdit(int)
{
    QString base = tablesComboBox->currentText();
    m_selectEditItems += itemsComboBox->currentText()+","; 
    selectEdit->setText(m_selectEditItems);
}

void Requete::fillComboConditions()
{
    QFile file(qApp->applicationDirPath()+"/../resources/conditions");
    if (!file.open(QIODevice::ReadOnly))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << "unable to find file conditions" ;
          return;
        }
    QTextStream stream(&file);
    while (stream.atEnd())
    {
        QString cond = stream.readLine();
        conditionsComboBox->addItem(cond);
        }
}

void Requete::writeAllSelectSentence()
{
    QString items = selectEdit->text();
    int count = items.count();
    if (items.endsWith(","))
    {
          items.remove(count-1,1);
        }
    QString base = tablesComboBox->currentText();
    QString fieldToCompare = fieldsComboBox->currentText();
    QString condition = conditionsComboBox->currentText();
    QString variable = variableEdit->text();
    QString allConditions;
    allConditions = fieldToCompare+" "+condition+"= '"+variable+"'";
    QString requete = QString("SELECT %1 FROM %2 WHERE %3").arg(items,base,allConditions);
    requeteLabel->setText(requete);
}

void Requete::search()
{
    QString resulttext;
    QString items = selectEdit->text();
    QStringList listOfItems;
    listOfItems = items.split(",",QString::SkipEmptyParts);
    int count = items.count();
    if (items.endsWith(","))
    {
          QMessageBox::information(0,trUtf8("info"),trUtf8("items.endsWith(",")")+QString::number(count),QMessageBox::Ok);
          items.remove(count-1,1);
        }
    QString base = tablesComboBox->currentText();
    QString fieldToCompare = fieldsComboBox->currentText();
    QString condition = conditionsComboBox->currentText();
    QString variable = variableEdit->text();
    QString allConditions;
    allConditions = fieldToCompare+" "+condition+"= '"+variable+"'";
    QString requete = QString("SELECT %1 FROM %2 WHERE %3").arg(items,base,allConditions);
    QSqlQuery q(m_db);
    if (!q.exec(requete))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << q.lastError().text() ;
          QMessageBox::warning(0,trUtf8("Warning"),trUtf8("Erreur : ")+q.lastError().text(),QMessageBox::Ok);          
        }
    while (q.next())
    {
        for (int i = 0; i < listOfItems.size(); ++i)
        {
              resulttext += q.value(i).toString()+"\n";
            }
        }
    Edit *edit = new Edit(this);
    edit->setTextOfResult(resulttext);
    edit->show();
}
