#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->addItems(m_listNGAP);
  connect(pushButton,SIGNAL(pressed()),this,SLOT(enregistreacte()));
  connect(pushButton_2,SIGNAL(pressed()),this,SLOT(closeAndInsertNewType()));
}

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);
  }

  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("");
			}
}

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

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