
#include "utilisateur.h"
#include "modifutil.h"
#include <common/constants.h>
#include <common/icore.h>
#include <common/settings.h>

using namespace Common;
using namespace Constants;
utilisateur::utilisateur(QString loginUser){
  qDebug() << "loginUser ="+loginUser;
  setupUi(this);
           //   m_db1               = QSqlDatabase::database(Constants::DB_DRTUX);
              m_accountancyDb               = QSqlDatabase::database(Constants::DB_ACCOUNTANCY);
  //----------attributs du widget----------------
  setAttribute     (Qt::WA_DeleteOnClose);
  setWindowFlags   (Qt::WindowStaysOnTopHint);
  setWindowModality(Qt::ApplicationModal);
  QString     reqBefore           = "SELECT id_usr , nom_usr , login ,password FROM utilisateurs WHERE login = '"+loginUser+"'";
  QSqlQuery queryFirst(m_accountancyDb);
            queryFirst.exec(reqBefore);
  QStringList listBefore;
  while(queryFirst.next()){
      QString id = queryFirst.value(0).toString();
      QString name = queryFirst.value(1).toString();
      QString pass = queryFirst.value(3).toString();
      listBefore << id+"="+name+"="+pass;
  }
  if(listBefore.size() > 1){
      QMessageBox::warning(0,tr("Information"),trUtf8("Deux noms ont le même login, erreur à corriger."),QMessageBox::Ok);
       }
       
  if(listBefore.size() == 0){
      listBefore << "1=Docteur=";
              m_listUtil         << "1=Docteur";
              m_listLogin        .insert("1","admin");
              m_listPassword     .insert("1","");
  }
  QStringList prefList = listBefore[0].split("=");
  qDebug() << __FILE__ << __LINE__;
  QString namePref = prefList[0]+" "+prefList[1];
  QString     requete             = "SELECT id_usr , nom_usr , login ,password FROM utilisateurs";
  QStringList listUtilisateurs;
  QSqlQuery query(m_accountancyDb) ;
      query                       .exec(requete);
      while(query.next()){
          QString idPrimkey  = query.value(0).toString();
          QString nom        = query.value(1).toString();         
          QString login      = query.value(2).toString();
          QString password   = query.value(3).toString();
              listUtilisateurs   << nom;
              m_listUtil         << idPrimkey+"="+nom  ;
              m_listLogin        .insert(idPrimkey,login);
              m_listPassword     .insert(idPrimkey,password);
             
      }
      
  //-----------------comboBox nom user--------------------------------------------
  m_listUtil                     .  sort();
                
  comboBox                       -> setEditable(true);
  comboBox                       -> addItems( listUtilisateurs );
  lineEdit_6                     -> setText(loginUser);
  lineEdit_5                     -> setText(prefList[2]);//password
  //--------------banque-----------------------------------
  QStringList listBank = queryBank(m_listLogin.key(loginUser).toInt());
       QString id_compte         = listBank[0];
       QString libelle           = listBank[1];
       QString bankName          = listBank[2];
       QString rib_code_banque   = listBank[3];
       QString rib_code_guichet  = listBank[4];
       QString rib_numcompte     = listBank[5];
       QString rib_cle           = listBank[6];
       QString solde_initial     = listBank[7];
       
      
  QStringList listCompte;
              listCompte << libelle;
  QStringList listBanque;
              listBanque << bankName;
  comboBox_3                     -> setEditable(true);
  comboBox_3                     -> addItems(listCompte);
  comboBox_5                     -> setEditable(true);
  comboBox_5                     -> addItems(listBanque);
  lineEdit_7                     -> setText(solde_initial); //initialisation du code
  lineEdit                       -> setText(rib_code_banque);
  lineEdit_2                     -> setText(rib_code_guichet);
  lineEdit_3                     -> setText(rib_numcompte);
  lineEdit_4                     -> setText(rib_cle);
  
  connect(pushButton  ,SIGNAL(pressed())       ,this,SLOT(enregistrer()));
  connect(pushButton_2,SIGNAL(pressed())       ,this,SLOT(close()));
  connect(pushButton_3,SIGNAL(pressed())       ,this,SLOT(modifier()));
  connect(pushButton_4,SIGNAL(pressed())       ,this,SLOT(choisir()));
  connect(comboBox    ,SIGNAL(highlighted(int)),this,SLOT(remplirLogin(int)));
}

utilisateur::~utilisateur(){
  m_listUtil                     .  clear();
}

void utilisateur::enregistrer(){
 /* if((lineEdit_6 -> text() == "")== false){
      QMessageBox::warning(0,tr("Attention"),trUtf8("Attention !\nVoulez vous un nouveau login pour cet utilisateur ?"),QMessageBox::Ok);
      }*/
  QString nomUsr                = comboBox->currentText();
  qDebug() << "nomUsr ="+nomUsr;
  QString login                    = lineEdit_6->text();
  QString password                 = lineEdit_5->text();
  QStringList listIdDrtux;
  QSqlQuery queryIdDrTux(m_accountancyDb) ;
            queryIdDrTux.exec("SELECT id_drtux_usr FROM utilisateurs");
            while( queryIdDrTux.next()){
                QString idDrtux = queryIdDrTux.value(0).toString();
                listIdDrtux << idDrtux;
            }
  listIdDrtux.sort();
  int idDrtuxUsr = 0;
  if(listIdDrtux.isEmpty()){
     idDrtuxUsr = 0;
  }
  else{
     qDebug() << "listIdDrtux.last() ="+listIdDrtux.last();
     idDrtuxUsr = listIdDrtux.last().toInt()+1;
  }
  QString libelle                  = comboBox_3->currentText();
  QString nomBanque                = comboBox_5->currentText();
  QString ribCodeBanque            = lineEdit->text();
  QString ribCodeGuichet           = lineEdit_2->text();
  QString ribNumCompte             = lineEdit_3->text();
  QString ribCle                   = lineEdit_4->text();
  double  soldeInitial             = lineEdit_7->text().toDouble();
  
  QString requeteUtilisateurs      = "INSERT INTO utilisateurs (nom_usr, login, password, id_drtux_usr) "
                                     "VALUES ('"+nomUsr+"','"+login+"','"+password+"',"+QString::number(idDrtuxUsr)+")";
  QSqlQuery queryUtilisateurs(m_accountancyDb);
            queryUtilisateurs      . exec(requeteUtilisateurs);
  int lastInsertId                = queryUtilisateurs.lastInsertId().toInt();
  qDebug() << "lastInsertId = "+QString::number(lastInsertId);
  QString requeteComptesBancaires  = "INSERT INTO comptes_bancaires "
                                     "(id_usr ,libelle ,titulaire ,nom_banque ,rib_code_banque ,"
                                     "rib_code_guichet ,rib_numcompte ,rib_cle ,solde_initial,remarque) "
                                     "VALUES ("+QString::number(lastInsertId)+" ,"
                                              "'"+libelle+       "',"
                                              "'"+nomUsr+        "',"
                                              "'"+nomBanque+     "',"
                                              "'"+ribCodeBanque+ "',"
                                              "'"+ribCodeGuichet+"',"
                                              "'"+ribNumCompte+  "',"
                                              "'"+ribCle+        "',"
                                              ""+QString::number(soldeInitial)+","
                                              " NULL)";

  QSqlQuery queryComptesBancaires(m_accountancyDb);
            if(!queryComptesBancaires  . exec(requeteComptesBancaires)){
                qDebug() << "Erreur ="+queryComptesBancaires.lastError().text()+"\n"+requeteComptesBancaires;
            }
  int lastInsertIdRapBank = queryComptesBancaires.lastInsertId().toInt();
  qDebug() << "lastInsertIdRapBank = "+QString::number(lastInsertIdRapBank);
  QString reqRapprochement_bank = "INSERT INTO rapprochement_bancaire (id_compte,solde) "
                                  "VALUES("+QString::number(lastInsertIdRapBank)+","
                                  ""+QString::number(soldeInitial)+");";
  QSqlQuery queryRapBank(m_accountancyDb);
            if(!queryRapBank.exec(reqRapprochement_bank)){
                qDebug() << "Erreur ="+queryRapBank.lastError().text()+"\n"+reqRapprochement_bank;
            }
  if((queryUtilisateurs.numRowsAffected() == 1) && 
     (queryComptesBancaires .numRowsAffected() == 1) && 
     (queryRapBank.numRowsAffected() == 1)){
      QMessageBox::information(0,tr("Information"),trUtf8("L'enregistrement a été effectué,\nla fenêtre va fermer"),QMessageBox::Ok);
      emit close();
  }
  
  
}

void utilisateur::remplirLogin(int indexComboBox){
  QString     ligneComboBox         = m_listUtil[indexComboBox];
  QStringList listComboBox          = ligneComboBox.split("=");
  QString     idKey                 = listComboBox[0];
  QString     loginAssocie          = m_listLogin.value(idKey);
              lineEdit_6           -> setText(loginAssocie);
  QString     passwordAssocie       = m_listPassword.value(idKey);
              lineEdit_5           -> setText(passwordAssocie);
  QStringList listCompte;
              listCompte << m_hashLibelle.value(idKey);
  QStringList listBanque;
              listBanque << m_hashBankName.value(idKey);
            
  comboBox_3                     -> addItems(listCompte);
  comboBox_5                     -> addItems(listBanque);
  lineEdit_7                     -> setText(m_hashSolde_initial.value(idKey)); //initialisation du code
  lineEdit                       -> setText(m_hashRib_code_banque.value(idKey));
  lineEdit_2                     -> setText(m_hashRib_code_guichet.value(idKey));
  lineEdit_3                     -> setText(m_hashRib_numcompte.value(idKey));
  lineEdit_4                     -> setText(m_hashRib_cle.value(idKey));
              
}

void utilisateur::modifier(){
  modifutil *modificationUtilisateurs = new modifutil;
  modificationUtilisateurs           -> show();
}

void utilisateur::choisir(){
  QString utilisateurchoisi = lineEdit_6->text();
  QString req = "SELECT id_usr FROM utilisateurs WHERE login = '"+utilisateurchoisi+"'";
  QSqlQuery query(m_accountancyDb);
            query.exec(req);
  QStringList list;
  while(query.next()){
      QString str = query.value(0).toString();
      list << str;
  }
  if(list.size()>1){
      QMessageBox::warning(0,tr("Information"),trUtf8("Deux fois le même login, erreur à corriger."),QMessageBox::Ok);
  }
  
  Common::ICore::instance()->settings()->setValue(S_UTILISATEUR_CHOISI,utilisateurchoisi);
  Common::ICore::instance()->settings()->setValue(S_ID_UTILISATEUR_CHOISI,list[0]);
  Common::ICore::instance()->settings()->setValue(S_COMPTE_PREFERENTIEL,comboBox_3->currentText());
}

QStringList utilisateur::queryBank(int idUsr){
  QString req ="SELECT  id_compte ,"
                       "libelle ,"
                       "nom_banque ,"
                       "rib_code_banque,"
                       "rib_code_guichet ,"
                       "rib_numcompte,"
                       "rib_cle ,"
                       "solde_initial "
                       "FROM comptes_bancaires "
                       "WHERE id_usr = '"+QString::number(idUsr)+"'";
   QSqlQuery queryBank(m_accountancyDb);
             queryBank.exec(req);
   QStringList listBank;
   while(queryBank.next()){
       QString id_compte         = queryBank.value(0).toString();
       QString libelle           = queryBank.value(1).toString();
       QString bankName          = queryBank.value(2).toString();
       QString rib_code_banque   = queryBank.value(3).toString();
       QString rib_code_guichet  = queryBank.value(4).toString();
       QString rib_numcompte     = queryBank.value(5).toString();
       QString rib_cle           = queryBank.value(6).toString();
       QString solde_initial     = queryBank.value(7).toString();
       listBank << id_compte +"="+ libelle +"="+bankName +"="+rib_code_banque +"="
                   +rib_code_guichet+"="+rib_numcompte+"="+rib_cle +"="+solde_initial ;
       m_hashId_compte       .insert(QString::number(idUsr),id_compte);
       m_hashLibelle         .insert(QString::number(idUsr),libelle );
       m_hashBankName        .insert(QString::number(idUsr),bankName);
       m_hashRib_code_banque .insert(QString::number(idUsr),rib_code_banque);
       m_hashRib_code_guichet.insert(QString::number(idUsr),rib_code_guichet);
       m_hashRib_numcompte   .insert(QString::number(idUsr),rib_numcompte);
       m_hashRib_cle         .insert(QString::number(idUsr),rib_cle);
       m_hashSolde_initial   .insert(QString::number(idUsr),solde_initial);
   }
    if(listBank.size() >1){
        QMessageBox::warning(0,tr("Warning 251"),trUtf8("Deux fois le même id, erreur à corriger."),QMessageBox::Ok);
    }
    if(listBank.size() == 0){
      listBank << "1=compte=ma banque=0000=0000=00000000=00=1";
      qDebug() << "listBank.size() = 0";
    }
    qDebug() << "list Result : "+listBank[0];
    QStringList listResult = listBank[0].split("=");
    return listResult;
}
