/***************************************************************************
 *   Copyright (C) 2008 by Dr Pierre-Marie DESOMBRE   *
 *   pm.desombre@medsyn.fr   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <QtGui>
#include <QtCore>
#include <QtSql>
#include "string.h"
#include "alarmedialog.h"
#include "utilpref.h"
#include "configalertedialog.h"
QString g_nomentre;
QString g_guidentre;
extern QString g_pathabsolu;
extern QString g_paramarg;
class QTextStream;

Alarmedialog::Alarmedialog(QWidget *parent):QWidget(parent,Qt::WindowStaysOnTopHint)
{
  setupUi(this);
  setAttribute(Qt::WA_DeleteOnClose);
  setAttribute(Qt::WA_CustomWhatsThis);
  QPalette palette;
  palette.setColor(QPalette::Button,Qt::blue);
  pushButton                           -> setPalette(palette);
  pushButton                           -> setWhatsThis(trUtf8("Ce bouton permet la sauvegarde de l'alerte choisie,"
                                                             " à la date affichée dans la base Alarmes de DrTux."));
  comboBox                             -> setWhatsThis(trUtf8("Ce menu déroulant permet de choisir une alerte préconfigurée "
                                                              "ou d'écrire une alerte en texte libre.\nSi on choisit "
                                                              "l'alerte préconfigurée, la date d'alerte s'affichera automatiquement."));
  pushButton_5                         -> setWhatsThis(trUtf8("Cliquez ici pour configurer vos alertes préétablies.")); 
  pushButton_6                         -> setToolTip(trUtf8("Cliquez sur ce bouton , déplacez la souris "
                                                             "sur la zone voulue, \ncliquez pour déclencher l'aide."));                                                           
  dateEdit                             -> setDate(QDate::currentDate());
  dateEdit                             -> setDisplayFormat("dd/MM/yyyy");
  timeEdit                             -> setTime(QTime::currentTime());
  
  //test datetime (anciennes dates en date)---------------------------------------
  
  QSqlQuery queryDateTime;
            queryDateTime.exec("SELECT Alarm_Date FROM Alarmes");
            if(queryDateTime.next()){
                QString dateTime = queryDateTime.value(0).toString();
                qDebug() << "datetime size = "+QString::number(dateTime.size());
                if(dateTime.size() < 12){
                qDebug() << "datetime is false";
                QSqlQuery queryAlter;
                          queryAlter.exec ("ALTER TABLE Alarmes MODIFY Alarm_Date datetime");
                QSqlQuery queryAlter2;          
                          queryAlter2.exec("ALTER TABLE Alarmes MODIFY Alarm_AlarmDate datetime");
                }
            }

//-----------------------------si argument utilisateur non récupéré dans medintux, on va le chercher dans le .ini.
  QString parametre = g_paramarg;
  if(parametre == " "){
      QStringList listepoint;
      QFile user(""+g_pathabsolu+"/utilisateur.ini");
      if(!user.open(QIODevice::ReadOnly))
          return;
      QTextStream point(&user);
          while(!point.atEnd()){
              QString lignepoint       = point.readLine();
              listepoint              << ""+lignepoint+"";
          }
  QString utilisateurphrase            = listepoint[3];
  utilisateurphrase                    . replace(" ","");
  QStringList utilliste                = utilisateurphrase.split("=");
  QString utilisateur                  = utilliste[0];
  g_paramarg                           = utilisateur;
  }
//---------------------si lancé hors de medintux, la variable g_nomentre est définie par "mafanfancherie"--------------------
  if(g_nomentre == "mafanfancherie")
  {
      m_texte                      =lineEdit->text();
      if(m_texte.isEmpty()){
          textenonchange();
      }

      connect(lineEdit,SIGNAL(textChanged(const QString&)),this,SLOT(textechange(const QString&)));

      comboBox                    ->setEditable(1);
      comboBox                    ->setInsertPolicy(QComboBox::NoInsert);
      QFile dedans(""+g_pathabsolu+"/alertes.ini");
         if(!dedans.open(QIODevice::ReadWrite | QIODevice::Text))
             return;
      QTextStream stream(&dedans);
          while(!stream.atEnd()){
              QString ligne       = stream.readLine();
              if(ligne.isEmpty() == true){
                  m_textes << "";
                  m_temps  << "0-0-0-0";
              }
              else{
                  QStringList lignepart = ligne.split("=");
                  QString ligne1        = lignepart[0];
                  QString lignetemps    = lignepart[1];
                  m_textes             << ""+ligne1+"";
                  m_temps              << ""+lignetemps+"";
	      }

          }
      comboBox->addItems(m_textes);
      
      comboBox_2                       ->setEditable(1);
      comboBox_2                       ->setInsertPolicy(QComboBox::NoInsert);

     //choix user preferentiel
     QStringList listepoint;
     QFile user(""+g_pathabsolu+"/utilisateur.ini");
     if(!user.open(QIODevice::ReadOnly))
         return;
     QTextStream point(&user);
         while(!point.atEnd()){
             QString lignepoint       = point.readLine();
             listepoint              << ""+lignepoint+"";
         }
     QString utilisateurphrase         = listepoint[3];
     utilisateurphrase                  .replace(" ","");
     QStringList utilliste             = utilisateurphrase.split("=");
     QString utilisateur               = utilliste[0];
     //choix user
     m_listelogin << ""+utilisateur+"";

     QSqlQuery query;
               query                  .exec("SELECT * FROM Personnes");
               while(query.next()){
                   m_login           = query.value(2).toString();
                   m_listelogin     << ""+m_login+"";
               }
     comboBox_2                      ->addItems(m_listelogin);


  connect(pushButton_3,   SIGNAL(pressed()),                           this,		 SLOT(utilisateurpreferentiel()));
  connect(dateEdit,    	  SIGNAL(dateChanged(const QDate&)),          calendarWidget,	 SLOT(setSelectedDate(const QDate&)));
  connect(calendarWidget, SIGNAL(clicked(const QDate&)),              dateEdit,		 SLOT(setDate(const QDate&)));
  connect(pushButton,     SIGNAL(clicked()),                          this,	         SLOT(ma_fonction_globale()));
  connect(pushButton_2,   SIGNAL(pressed()),                          this,		 SLOT(close()));
  connect(pushButton_5,   SIGNAL(pressed()),                          this,		 SLOT(configureralerte()));
  connect(pushButton_6,   SIGNAL(pressed()),                          this,              SLOT(whatsthismode()));
  connect(comboBox,       SIGNAL(currentIndexChanged(const QString&)),this,		 SLOT(sicomboboxchange(const QString&)));
  }
  //----------------------------------------------------
  else //si Alarmes est déclenché dans MedinTux
  //----------------------------------------------------
  {
  tableView->hide();
  QSqlQuery query4;
            query4.exec("SELECT FchGnrl_NomDos,FchGnrl_Prenom FROM IndexNomPrenom WHERE FchGnrl_IDDos='"+g_guidentre+"';");
            while(query4.next()){
                m_donneenom = query4.value(0).toString();
                m_donneeprenom = query4.value(1).toString();
                m_nomprenom << ""+m_donneenom+"" << ""+m_donneeprenom+"" ;
	    }
  if(m_nomprenom.size()> 2){
       QMessageBox::critical(0,tr("erreur critique"),trUtf8("il existe probablement deux guid pour le même dossier"
						            " \n ce qui est dangereux"),QMessageBox::Ok);
       QTimer::singleShot(1000,qApp,SLOT(closeAllWindows()));
  }

  lineEdit->insert(""+m_donneenom+";"+m_donneeprenom+"");
  m_texte=lineEdit->text();

  comboBox->setEditable(1);
  comboBox->setInsertPolicy(QComboBox::NoInsert);
  QFile dedans(""+g_pathabsolu+"/alertes.ini");
  if(!dedans.open(QIODevice::ReadOnly | QIODevice::Text))
      return;
  QTextStream stream(&dedans);
      while(!stream.atEnd()){
          QString ligne             = stream.readLine();
          if(ligne.isEmpty() == true){
              m_textes << "";
              m_temps  << "0-0-0-0";
          }
          else{
              QStringList lignepart = ligne.split("=");
              QString ligne1        = lignepart[0];
              QString lignetemps    = lignepart[1];
              m_textes           << ""+ligne1+"";
              m_temps            << ""+lignetemps+"";
	 }

      }

  comboBox->addItems(m_textes);
  m_texteaffiche = comboBox->currentText();

  comboBox_2->setEditable(1);
  comboBox_2->setInsertPolicy(QComboBox::NoInsert);

  //choix user
  m_listelogin << ""+g_paramarg+"";

  QSqlQuery query;
            query.exec("SELECT * FROM Personnes");
                while(query.next()){
                    m_login = query.value(2).toString();
                    m_listelogin << ""+m_login+"";
                }
  comboBox_2->addItems(m_listelogin);
  m_login = "";

  connect(pushButton_3,        SIGNAL(pressed()),                 this,          SLOT(utilisateurpreferentiel()));
  connect(dateEdit,            SIGNAL(dateChanged(const QDate&)), calendarWidget,SLOT(setSelectedDate(const QDate&)));
  connect(calendarWidget,      SIGNAL(clicked(const QDate&)),     dateEdit,      SLOT(setDate(const QDate&)));
  connect(pushButton,          SIGNAL(clicked()),                 this,          SLOT(ma_fonction_globale()));
  connect(pushButton_2,        SIGNAL(pressed()),                 this,          SLOT(close()));
  connect(pushButton_5,        SIGNAL(pressed()),                 this,          SLOT(configureralerte()));
  connect(pushButton_6,        SIGNAL(pressed()),                 this,          SLOT(whatsthismode()));
  connect(comboBox,            SIGNAL(activated(const QString&)), this,          SLOT(sicomboboxchange(const QString&)));
  }
}
/////////////////////////////////////////////////////////////////////
//fin du constructeur
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//deux fonctions déclenchées si le logiciel n'est pas lancé dans MedinTux
///////////////////////////////////////////////////////////
void Alarmedialog::textechange(const QString &m_texte){

  model = new QSqlTableModel;
  model->setTable("IndexNomPrenom");

  model->setFilter("FchGnrl_NomDos LIKE '"+m_texte+"%'");
  model->setSort(1,Qt::AscendingOrder);//on classe par ordre alphabétique

  model->select();

  proxymodel = new QSortFilterProxyModel;
  proxymodel->setSourceModel(model);
  tableView->setModel(proxymodel);
  tableView->setColumnHidden(0,true);//on cache la colonne ID_Primkey
  tableView->setColumnHidden(3,true);//on cache la colonne FchGnrl_IDDos
  tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
  tableView->setSelectionMode(QAbstractItemView::SingleSelection);
  tableView->resizeColumnsToContents();
}
//
void Alarmedialog::textenonchange(){
  model = new QSqlTableModel;
  model->setTable("IndexNomPrenom");
  model->setSort(1,Qt::AscendingOrder);//on classe par ordre alphabétique
  model->select();

  proxymodel = new QSortFilterProxyModel;
  proxymodel->setSourceModel(model);

  tableView->setModel(proxymodel);
  tableView->setColumnHidden(0,true);//on cache la colonne ID_Primkey
  tableView->setColumnHidden(3,true);//on cache la colonne FchGnrl_IDDos
  tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
  tableView->setSelectionMode(QAbstractItemView::SingleSelection);
  tableView->resizeColumnsToContents();
}
/////////////////////////////////////////////////////////////////////
//fonction principale
//////////////////////////////////////////////////////////////////////
void Alarmedialog::ma_fonction_globale()
{
  db                          = QSqlDatabase::database();
  //recupere la date du jour de l'ordi puis la transforme dans le bon format.
  m_date2                     = QDate::currentDate();
  m_timeCurrent               = QTime::currentTime();
  m_datecourante              = m_date2.toString("yyyy-MM-dd");
  QDateTime dateTimeCurrentDt ( m_date2,m_timeCurrent );
  QString dateTimeCurrent     = dateTimeCurrentDt.toString("yyyy-MM-dd hh:mm:ss");
  
  //recupere la date et l'heure de l'alarme selectionnee
  m_date3                     = calendarWidget->selectedDate();
  m_dateselect                = m_date3.toString("yyyy-MM-dd");
  m_timeSelect                = timeEdit->time(); // hh:mm:ss
  QDateTime dateTimeChoisieDt ( m_date3, m_timeSelect);   
  QString    dateTimeChoisie  = dateTimeChoisieDt.toString("yyyy-MM-dd hh:mm");
     
  //--------recuperation de l'identifiant du dossier patient hors medintux--------------------
  if(g_nomentre == "mafanfancherie"){
    if(db.isOpen() == false){
        QMessageBox::warning(0,tr("erreur"),trUtf8("database n'est pas ouvert"),QMessageBox::Ok);
    }
    m_index                   = tableView->QAbstractItemView::currentIndex();
    int row                   = m_index.row();
    QModelIndex n             = proxymodel->index(row,1,QModelIndex());
    QModelIndex pr            = proxymodel->index(row,2,QModelIndex());
    QModelIndex i             = proxymodel->index(row,3,QModelIndex());
    m_donneenom               = n.data(Qt::DisplayRole).toString();
    m_donneeprenom            = pr.data(Qt::DisplayRole).toString();
    m_donneeid                = i.data(Qt::DisplayRole).toString();

    m_textedit                = comboBox->currentText();
    m_eccehomo                = comboBox_2->currentText();

   //insere les variables obtenues dans la table DrTuxTest > Alarmes
    QString requete1          = "INSERT INTO Alarmes (TextAlarme, Alarm_Date, Alarm_AlarmDate, Nom, Prenom,Alarm_IDDos,Alarm_utilisateur)"
                                "VALUES('"+m_textedit+"',"
                                "'"+dateTimeChoisie+"'," //datetime de l alarme a venir
                                "'"+dateTimeCurrent+"'," //datetime courrante
                                "'"+m_donneenom+"',"
                                "'"+m_donneeprenom+"',"
                                "'"+m_donneeid+"',"
                                "'"+m_eccehomo+"')";
    QSqlQuery query2(db);
             query2          . exec(requete1 );
    comboBox                -> clearEditText();

    QString textea           = "<html><body><font size = 3 color = ""red""><bold>votre alerte\na été "
                               "enregistrée</bold></font></body></html>";
    std::string texteastring = textea.toStdString();
    const char *texteachar   = texteastring.c_str();
    label_4                  ->setText(trUtf8(texteachar));
  }
//------------------------recuperation dans medintux-------------------------------------------------------
  else {
  if(db.isOpen() == false){
      QMessageBox::warning(0,tr("erreur"),trUtf8("database n'est pas ouvert"),QMessageBox::Ok);
  }
  m_donneeid = g_guidentre;
  m_textedit = comboBox->currentText();
  m_eccehomo = comboBox_2->currentText();
  //insere les variables obtenues dans la table DrTuxTest > Alarmes
  QString requete2           = "INSERT INTO Alarmes (TextAlarme, Alarm_Date, Alarm_AlarmDate, Nom, Prenom,Alarm_IDDos,Alarm_utilisateur)"
                                "VALUES('"+m_textedit+"',"
                                "'"+dateTimeChoisie+"',"
                                "'"+dateTimeCurrent+"',"
                                "'"+m_donneenom+"',"
                                "'"+m_donneeprenom+"',"
                                "'"+m_donneeid+"',"
                                "'"+m_eccehomo+"')";
  QSqlQuery query2(db);
            query2           . exec(requete2);
  comboBox                   ->clearEditText();

  QString textea            = "<html><body><font size = 3 color = ""red""><bold>votre alerte\na été "
                              "enregistrée</bold></font></body></html>";
  std::string texteastring  = textea.toStdString();
  const char *texteachar    = texteastring.c_str();
  label_4                   ->setText(trUtf8(texteachar));

  }
  //fermeture automatique du widget
  QTimer::singleShot(2000,this,SLOT(close()));
}

void Alarmedialog::utilisateurpreferentiel()
{
  QString utilisateurchoisi = comboBox_2->currentText();
  utilprefdialog *dialog = new utilprefdialog(utilisateurchoisi);
  dialog->exec();
  pushButton_3->setEnabled(false);
			}

void Alarmedialog::sicomboboxchange(const QString &m_texteaffiche){

  QDate dateaffichee               = QDate::currentDate();

  QString texte;
  QString tempsdate;
  int temps;
  int newjour;
  int newmois;
  int newannee;
      texte                        = m_texteaffiche;


  qDebug() << "3";
  int indextexte                   = m_textes.indexOf(""+texte+"",0);
qDebug() << "4 ="+QString::number(indextexte);
  tempsdate                        = m_temps[indextexte];//minutes-day-month-year
qDebug() << "5 ="+tempsdate;
	if(tempsdate.isEmpty()){
   	QMessageBox::warning(0,tr("erreur"),trUtf8("alertes.ini est corrompu"),QMessageBox::Ok);
	}
	qDebug() << "1";
  QStringList decouptempsdate     = tempsdate.split("-");
  temps                           = decouptempsdate[0].toInt();
  newjour                         = decouptempsdate[1].toInt();
  newmois                         = decouptempsdate[2].toInt();
  newannee                        = decouptempsdate[3].toInt();
  qDebug() << "2";
    if(texte == ""){
    qDebug() << "dans temps";
      temps    = 0;
      newjour  = 0;
      newmois  = 0;
      newannee = 0 ;
    }

	if(temps < 1440 && temps > 0 && newjour == 0 && newmois == 0 && newannee == 0 ){
	    QTime time            = timeEdit->time();
	    int tempssec          = temps*60; // temps en secondes
	    time                   .addSecs(tempssec);
	    timeEdit             -> setTime(time);
	}
	else if(temps == 0 && newjour == 0 && newmois == 0 && newannee == 0 ){
	    qDebug() << "dans else if 0";
	    dateEdit->setDate(QDate::currentDate());
	    timeEdit -> setTime(QTime::currentTime());
 	}
	else{
	    QDate nouvelledate;
	    nouvelledate = dateaffichee.addDays(newjour);
	    nouvelledate = dateaffichee.addMonths(newmois);
	    nouvelledate = dateaffichee.addYears(newannee);
	    dateEdit->setDate(nouvelledate);
    	}
}
void Alarmedialog::configureralerte(){
  configalertedialog *config = new configalertedialog;
  config                     ->show();
}

void Alarmedialog::whatsthismode()
{
  QWhatsThis::enterWhatsThisMode();
 }
