#include <QtCore>
#include <QtGui>
#include <QtSql>
#include <common/icore.h>
#include <common/settings.h>
#include "actesdispo.h"
#include "../constants.h"
using namespace Common;
using namespace Constants;
actesdispo::actesdispo()
{
  m_db = QSqlDatabase::database(Constants::DB_ACCOUNTANCY);
  setupUi(this);
  comboBox->setEditable(true);
  comboBox->setInsertPolicy(QComboBox::InsertAtBottom);
  /*m_fileNGAP.setFileName(Common::ICore::instance()->settings()->applicationBundlePath()+"/typesNGAP.ini");
  if(!m_fileNGAP.open(QIODevice::ReadWrite|QIODevice::Text)){
      qWarning() << "typesNGAP cannot open\n" << __FILE__ << " " << QString::number(__LINE__);
  }
  QTextStream stream(&m_fileNGAP);

  while(!stream.atEnd()){
      QString s = stream.readLine();
      if(!s.isEmpty()){
          m_listNGAP << s;
      }
  }*/

  comboBox_2->setEditable(true);
  comboBox_2->setInsertPolicy(QComboBox::NoInsert);
  QSqlQuery query(m_db);
  QString req = QString("SELECT %1 ,%2 ,%3, %4, %5 FROM actes_disponibles")
               .arg("nom_acte","desc_acte","type","montant_total","montant_tiers");
  if(!query.exec(req)){
      qWarning() << query.lastError().text() << " " << __FILE__ << " " << QString::number(__LINE__);
      }
  int key = 0;
  while(query.next()){
      key++;
      QString actName = query.value(0).toString();
      QString type = query.value(2).toString();
      QStringList listResult;
       listResult << actName                  // nom acte
                  << query.value(1).toString() //description acte
                  << type //type (consultation , visite, acte en K)
                  << query.value(3).toString() //montant
                  << query.value(4).toString();//montant/3
      m_mapNGAP.insert(key,listResult);
      comboBox_2->addItem(actName);
      comboBox->addItem(type);
      }
      QString comboDeuxText = comboBox_2->currentText();
      fillLabelsAndCombo(comboDeuxText);
  connect(pushButton,SIGNAL(pressed()),this,SLOT(enregistreacte()));
  connect(pushButton_2,SIGNAL(pressed()),this,SLOT(closeAndInsertNewType()));
  connect(comboBox_2,SIGNAL(activated(const QString &)),this,SLOT(fillLabelsAndCombo(const QString &)));
}

actesdispo::~actesdispo(){}

void actesdispo::enregistreacte(){
	QString nomacte 	= lineEdit->text();
	QString description 	= lineEdit_2->text();
	QString type 		= comboBox->currentText();
	QString valeurtotale	= lineEdit_4->text();
	QString valeurtiers     = lineEdit_5->text();

  /*if(!m_listNGAP.contains(type)){
      m_fileNGAP.close();
      if(!m_fileNGAP.open(QIODevice::ReadWrite|QIODevice::Text)){
          qWarning() << "typesNGAP cannot open\n" << __FILE__ << " " << QString::number(__LINE__);
      }
      QTextStream s(&m_fileNGAP);
      m_listNGAP.append(type);
      QString str;
      foreach(str,m_listNGAP){
          s << str+"\n";
      }
      comboBox->clear();
      comboBox->addItems(m_listNGAP);
  }*/
  bool answer = false;
  QSqlQuery queryAsk(m_db);
  QString reqAsk = QString("SELECT %1 FROM %2")
                   .arg("nom_acte","actes_disponibles");
  if(!queryAsk.exec(reqAsk)){
      qWarning() << queryAsk.lastError().text() << "\n" << __FILE__ << " " << QString::number(__LINE__);
      }
  while(queryAsk.next()){
      QString act = queryAsk.value(0).toString();
      if(act == lineEdit->text().trimmed()){
          answer = true;
          }
      }
  if(answer == false){
      QSqlQuery query(m_db);
      if(!query.exec("INSERT INTO actes_disponibles (nom_acte,desc_acte,type,montant_total,montant_tiers)"
		"VALUES( '"+nomacte+"',"
			"'"+description+"',"
			"'"+type+"',"
			"'"+valeurtotale+"',"
			"'"+valeurtiers+"')")){
			    qWarning() << query.lastError().text() << "\n" << __FILE__ << " " << QString::number(__LINE__);
			}
			if(query.numRowsAffected()== 1){
			    QMessageBox::information(0,tr("information"),
			    trUtf8("Les informations\nont été intégrées."),QMessageBox::Ok);
			    /*lineEdit->setText("");
	                    lineEdit_2->setText("");
	                    lineEdit_4->setText("");
	                    lineEdit_5->setText("");*/
			}
			else {
			    QMessageBox::warning(0,tr("attention"),trUtf8("Echec insertion !"),QMessageBox::Ok);
			    /*lineEdit->setText("");
	                    lineEdit_2->setText("");
	                    lineEdit_4->setText("");
	                    lineEdit_5->setText("");*/
			}
  }
  else{
      QSqlQuery queryAlter(m_db);
      QString reqAlter = QString("UPDATE %1 SET desc_acte = '%2',type = '%3',"
                                 "montant_total = '%4',montant_tiers = '%5' WHERE nom_acte = '%6'")
                        .arg("actes_disponibles",description,type,valeurtotale,valeurtiers,nomacte);
      if(!queryAlter.exec()){
          qWarning() << queryAlter.lastError().text() << "\n" << __FILE__ << " " << QString::number(__LINE__);
          }
      }
}

void actesdispo::closeAndInsertNewType(){
  emit close();
}

void actesdispo::on_lineEdit_4_textChanged(){
    lineEdit_5->setText(QString::number((lineEdit_4->text().toDouble())/3));
}

void actesdispo::fillLabelsAndCombo(const QString & act){
    QString strAct = act;
    QString description;
    QString type;
    QString price;
    QString thirdPrice;
    QMapIterator <int,QStringList> it(m_mapNGAP);
    while(it.hasNext()){
        it.next();
        QStringList list = it.value();
        if(list.contains(strAct)&& list[0].count() == strAct.count()){
            description = list[1];
            type = list[2];
            price = list[3];
            thirdPrice = list[4];
            lineEdit->setText(strAct);
            lineEdit_2->setText(description);
            comboBox->setItemText(1,type);
            lineEdit_4->setText(price);
            lineEdit_5->setText(thirdPrice);
            }
        }

}
