
/***************************************************************************
 *   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 "math.h"
#include "lecturedialog.h"
#include "modifierdialog.h"
#include "lectlabel.h"
#include "parametre.h"

extern QString g_pathabsolu;
extern int g_increment;
Lecturalarme::Lecturalarme(QWidget *parent)
:QWidget(parent)
{
  setupUi(this);
  int timing                             = 100000;
  QString textelabel                     = "Lecture des alarmes avant le "+QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss")+". "
                                           "Pour lire tout c'est le bouton <i>Voir toutes<i/>";
  std::string textelabelstring           = textelabel.toStdString();
  const char *textelabelchar             = textelabelstring.c_str();
  label                                 -> setText(textelabelchar);
  setAttribute(Qt::WA_DeleteOnClose);
  QFile file(g_pathabsolu+"/timing.ini");
  if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){
      QMessageBox::warning(0,trUtf8("Erreur"),trUtf8("timing.ini ne peut pas être ouvert."),QMessageBox::Ok);
      }
  QTextStream stream(&file);
  while(!stream.atEnd()){
      QString line                        = stream.readLine();
              line.replace(" ","");
      QStringList list                    = line.split("=");
      timing                              = list[1].toInt();
      }
  m_modele                               = new QSqlTableModel;
  afficher();
  

  m_x = m_modele                         -> rowCount();

  connect(pushButton,  SIGNAL(clicked()),this,SLOT(voir_et_changer()));
  connect(pushButton_2,SIGNAL(clicked()),this,SLOT(voir_et_changer()));
  connect(pushButton_3,SIGNAL(clicked()),this,SLOT(effacer()));
  connect(pushButton_4,SIGNAL(clicked()),this,SLOT(fermer()));
  connect(pushButton_5,SIGNAL(clicked()),this,SLOT(enregistrer()));
  connect(pushButton_6,SIGNAL(clicked()),this,SLOT(parametrer()));

  m_timer                                 = new QTimer(this);
  m_timer                                -> setInterval(timing);
  connect(m_timer,SIGNAL(timeout()),this,SLOT(labelalerte()));
  m_timer                                -> start();
  //this->installEventFilter();
}

Lecturalarme::~Lecturalarme(){
    delete m_modele;
    delete m_timer;
    m_x = 0;
    }
void Lecturalarme::voir_et_changer()
{
  modifierdialog *modif = new modifierdialog;
  modif->show();
  /*if(modif->exec() == QDialog::Accepted)
  {
  modif->modifierdialog::effacer(modif);
  }*/
}

void Lecturalarme::effacer()
{
  QString id;
  QModelIndex index                     = tableView->QAbstractItemView::currentIndex();
  int i                                 = index.row();
  // id = c_ident[i];
  //QSqlQuery query;
  //query.exec("DELETE FROM Alarmes WHERE Alarm_IDDos = '"+id+"'");
  m_modele                             -> removeRows(i,1,QModelIndex());
 /* if((m_modele -> submitAll())== false){
      QMessageBox::warning(0,tr("erreur"),trUtf8("Problème d'enregistrement 97 dans la base Alarmes."),QMessageBox::Ok);
      }*/
}


void Lecturalarme::enregistrer()
{
  QString alarmeId                 = "";
  QString textealarme              = "";
  int alarmvalid                   = 0;
  QString utilisateur              = "";

  QSqlQuery query;
  if((query.exec("SELECT Alarm_IDDos,TextAlarme,Alarm_valid,Alarm_utilisateur FROM Alarmes "
                 "WHERE Alarm_Date <= '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"'"))==false){
      QMessageBox::warning(0,tr("erreur"),trUtf8("Problème de connexion à la base Alarmes."),QMessageBox::Ok);
      }
  else{
      while(query.next())
     {
         alarmvalid = query.value(2).toInt();
         bool b = alarmvalid==1;
             if(b == false)
             {
                 alarmeId             = query.value(0).toString();
                 utilisateur          = query.value(3).toString();
                 textealarme          = query.value(1).toString();
                 textealarme           .replace(QRegExp("\\n"),"<br/>");
                 QString deuxpoints   = " :";
                 textealarme = "<html><head><meta name=\"qrichtext\" content=\"1\" /></head>"
                               "<body style=\"font-size:9pt;font-family:Courier\"><p>"
                               "<span style=\"font-size:16pt;text-decoration:underline;color:#0000ff\">"
                               ""+textealarme+"</span>"+deuxpoints+"</p></body></html>";

                 QSqlQuery query2;
                 query2.exec("INSERT INTO RubriquesBlobs (RbDate_PrimKey,RbDate_DataRub,RbDate_IDDos) "
                             "VALUES (NULL,'"+textealarme+"','"+alarmeId+"')");
                 QString lastid = query2.lastInsertId().toString();

                 QSqlQuery query3;
                 query3.exec("INSERT INTO RubriquesHead"
                             "(RbDate_PrimKey,RbDate_IDDos,RbDate_TypeRub,RbDate_NomDate,RbDate_SubTypeRub,"
                             "RbDate_Date,RbDate_CreateUser,RbDate_CreateSignUser,RbDate_Duree,"
                             "RbDate_Ref_NumDoss,RbDate_RefBlobs_Primkey)"
                             "VALUES (NULL,'"+alarmeId+"',20030000,'Alarme',NULL,'"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"',"
                             "'"+utilisateur+"','"+utilisateur+"',0,0,'"+lastid+"')");

                 QSqlQuery query4;
                 query4.exec("UPDATE Alarmes SET Alarm_valid = '1' WHERE Alarm_IDDos = '"+alarmeId+"'");

             }//if
       }//while

  }//else
  this->showMinimized();
}

void Lecturalarme::fermer(){
  emit QApplication::closeAllWindows();
}

void Lecturalarme::labelalerte()
{
  QSqlTableModel *modele2         = new QSqlTableModel;
  modele2                         ->setTable ("Alarmes");
  modele2                         ->setFilter("Alarm_Date <= '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"'");
  modele2                         ->select();
  m_y                             = modele2->rowCount();
//////////////////////////déclenchement du widget d'alerte/////////////////////////////////
  if(m_y-m_x!=0){//si rajout d'une rangée depuis que le constructeur est lancé

      int z                       = m_y-1;
      QModelIndex indexnom        = modele2->index(z,4,QModelIndex());
      QModelIndex indexprenom     = modele2->index(z,5,QModelIndex());
      QModelIndex indexcause      = modele2->index(z,1,QModelIndex());
      QModelIndex indexValide     = modele2->index(z,7,QModelIndex());
      QString nom                 ="";
      QString prenom              ="";
      QString cause               = "";
      QString nomprenomcause      = "";//récupération du nom, du prénom et de la cause de l'alerte.
      int     Valide              = 0;
      nom                         = modele2->data(indexnom,Qt::DisplayRole).toString();
      prenom                      = modele2->data(indexprenom,Qt::DisplayRole).toString();
      cause                       = modele2->data(indexcause,Qt::DisplayRole).toString();
      nomprenomcause              = nom+","+prenom+"<br>pour "+cause;
      Valide                      = modele2->data(indexValide,Qt::DisplayRole).toInt();
      qDebug() << "valide ="+QString::number(Valide);
////////////////////////////on lance le popup avec son argument.
  m_labelclic                     = new mylabel(nomprenomcause);
      if((Valide == 1) == false){
          m_labelclic            -> show();

          if((this->isMinimized())== false){
              m_modele          -> clear();
              afficher();
              }
      }

  m_x++;//on incrémente pour ne pas relancer le widget pour la  même alerte.
  g_increment++;//pour taille fenêtre
  //delete m_labelclic;

  }
}

void Lecturalarme::lanceslot(){//ne sert à rien
  this->showMaximized();
}

bool Lecturalarme::event(QEvent *event){
  if(event->type() == QEvent::WindowStateChange){
     if(this->windowState() == Qt::WindowMinimized){
          afficher();
      }
  }
  
  return QWidget::event(event);
}

void Lecturalarme::afficher(){

  m_modele               -> setTable("Alarmes");
  m_modele               -> setFilter("Alarm_Date <= '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"'");
    if(!m_modele->select()){
      QMessageBox::warning(0,tr("attention!"),trUtf8("la table Alarmes n'est pas installée ou son nom dans la base est faux."
              "\nVeuillez lancer Alarmes dans l'observation\nqui vous guidera pas à pas,\nou bien setup."),QMessageBox::Warning,QMessageBox::Ok);
  }
  tableView              -> setModel(m_modele);

  tableView              -> setColumnHidden(0,true);
  tableView              -> setColumnHidden(3,true);
  tableView              -> setColumnHidden(6,true);
  tableView              -> horizontalHeader()->setResizeMode(QHeaderView::Stretch);
  tableView              -> verticalHeader()  ->setResizeMode(QHeaderView::Stretch);
  tableView              -> setSelectionBehavior(QAbstractItemView::SelectRows);
  tableView              -> setSelectionMode(QAbstractItemView::SingleSelection);
  tableView              -> show();
}


void Lecturalarme::parametrer(){
  parametre *param       =  new parametre;
             param       -> show();

}






