#include <QtGui>
#include <QtCore>
#include <QtSql>
#include "wiz1.h"
#include "connexion.h"
#include "mdp.h"

  QString g_path;
  extern QString g_pathabsolu;
  QString texte              = "";
  QString texteHtml          = "";

wiz1::wiz1(){
  g_path                     = "";
  setOption(QWizard::NoBackButtonOnStartPage,true);

  setPage(pageUn    ,new page1);
  setPage(pageDeux  ,new page2);
  setPage(pageFinale,new pageFin);
  setStartId(pageUn);

  
}

wiz1::~wiz1(){}

page1::page1(){
  setupUi(this);
    //----------verification de la presence de DrTux---------------------------------
   /* QDir dirDrTux               (g_pathabsolu+"/../drtux");
    if (dirDrTux . exists() == false){
      QMessageBox::warning(0,trUtf8("Erreur"),trUtf8("Le répertoire Pensebetux n'est pas placé dans le répertoire Programmes "
                                                     "à côté de DrTux.\n"
                                                     "L'installation ne peut pas se faire correctement. "),QMessageBox::Ok);
      wizard()->close();
      
    }*/
  //------------------------------------------------------------------------------
   texte             = trUtf8("Ce programme permet l'installation de Pensebetux.<br/>"
                                     "Ce programme permet de mettre une alerte pour un patient et une tâche à une date donnée.<br/>"
                                     "Il s'intègre très bien à DrTux en récupérant le nom et le prénom du patient.<br/>"
                                     "Veuillez lancer le setup.");
  texteHtml         = "<html><body><font size = 4 color = ""blue"">"+texte+"</font></body></html>";
  label                     -> setText(texteHtml);
  label                     -> setWordWrap(true);
    label                   -> resize(380,200);
  QGridLayout *layout       = new QGridLayout(this);
               layout      -> addWidget(label,0,0);
  setLayout                   (layout);

  
}

page1::~page1(){}

page2::page2(){
  setupUi(this);
             m_model          = new QDirModel;
           
             m_model         -> setFilter(QDir::AllDirs|QDir::NoDotAndDotDot);
             m_tree           = new QTreeView(this);
             m_tree          -> setModel(m_model);
             m_tree          -> resize(380,200);
             m_tree          -> setExpanded(m_model->index(0,0,QModelIndex()),true);
             m_tree          -> header() -> setResizeMode(0,QHeaderView::ResizeToContents);
             m_tree          -> show();

  texte             = trUtf8("Veuillez choisir l'emplacement de MedinTux et cliquer dessus.");
  texteHtml         = "<html><body><font size = 4 color = ""green"">"+texte+"</font></body></html>";
  label                    -> setText(texteHtml);
  label                    -> resize(380,70);
  QGridLayout *layout       = new QGridLayout(this);
               layout      -> addWidget(label,0,0);
               layout      -> addWidget(m_tree,1,0);
  setLayout                   (layout);

  connect(m_tree,SIGNAL(activated(const QModelIndex&)),this,SLOT(choixMedintux(const QModelIndex&)));

}

page2::~page2(){}

pageFin::pageFin(){
  setupUi(this);
  setFinalPage(true);

  texte                     = trUtf8("Veuillez cliquer sur Test pour vérifier la bonne installation du menu de Pensebetux.");
  texteHtml                 = "<html><body><font size = 4 color = ""blue"">"+texte+"</font></body></html>";
  test                      =  new QPushButton;
  test                      -> setText("Test");
  test                      -> setEnabled(true);
  test                      -> resize(150,70);  
  test                      -> setMinimumHeight(70);
  test                      -> setMinimumWidth(150);
  test                      -> setMaximumHeight(70);
  test                      -> setMaximumWidth(150);
  label                     -> resize(380,70);
  label                     -> setText(texteHtml);
  label                     -> setWordWrap(true);
  QGridLayout *layout       =  new QGridLayout(this);
               layout      ->  addWidget(label,0,0,1,3);
               layout      ->  addWidget(test,1,1,1,1);
  setLayout                   (layout);

  connect(test,SIGNAL(pressed()),this,SLOT(resultat()));
}

pageFin::~pageFin(){}

void page2::installCompta(){
   
  //------------creation dossiers dans ../../drtux/bin/Ressources/Menus/---------
  QDir  dirMenus              (g_path+"/Programmes/drtux/bin/Ressources/Menus");
        dirMenus             . mkdir("Alarmes");
        dirMenus             . mkdir("LectureAlertes");
  QFile alarmesText          ( g_path+"/Programmes/pensebetux/Menus/Alarmes/definition.txt" );
  QFile alarmesPng           ( g_path+"/Programmes/pensebetux/Menus/Alarmes/alarmes.png");
  QFile lectureText          ( g_path+"/Programmes/pensebetux/Menus/LectureAlertes/definition.txt" );
  QFile lecturePng           ( g_path+"/Programmes/pensebetux/Menus/LectureAlertes/lecture.png");
        alarmesText          . copy(g_path+"/Programmes/drtux/bin/Ressources/Menus/Alarmes/definition.txt");
        alarmesPng           . copy(g_path+"/Programmes/drtux/bin/Ressources/Menus/Alarmes/alarmes.png");
        lectureText          . copy(g_path+"/Programmes/drtux/bin/Ressources/Menus/LectureAlertes/definition.txt");
        lecturePng           . copy(g_path+"/Programmes/drtux/bin/Ressources/Menus/LectureAlertes/lecture.png");

}

void page2::choixMedintux(const QModelIndex& index){
  QString indexMedintux       = m_model -> data(index).toString();
  g_path                      = m_model -> filePath(index);
  texte               = trUtf8("le chemin de votre dossier MedinTux est : ")+g_path;
  QString lpath               = "<html><body><font size=4 color = ""red""><bold>"+texte+"</bold></font></body></html>";
  label                     -> setText(lpath);
  label                     -> setWordWrap(true);
  if((g_path.contains("medintux",Qt::CaseInsensitive))== false){
      QMessageBox mess;
      QPushButton *OKButton  = mess . addButton(tr("Ok"),QMessageBox::AcceptRole);
      QPushButton *AbButton  = mess . addButton(trUtf8("Quitter"),QMessageBox::RejectRole);
      mess                   . setText(trUtf8("L'item choisi ne contient pas'MedinTux',\nl'installation ne peut pas se faire."));
      mess                   . exec();
      if(     mess.clickedButton() == OKButton){
          mess.close();
          return;
      }
      else if(mess.clickedButton() == AbButton){
          qApp-> closeAllWindows();
          return;
      }
  }
  emit installCompta();
  emit instalTables();
}

void pageFin::resultat(){
  QString texte = "";
  QString texteHtml = "";
  if(g_path == ""){
      QMessageBox mess;
      QPushButton *OKButton  = mess . addButton(tr("Ok"),QMessageBox::AcceptRole);
      QPushButton *AbButton  = mess . addButton(trUtf8("Quitter"),QMessageBox::RejectRole);
      mess                   . setText(trUtf8("Avez vous cliqué ou double cliqué "
                                              "sur un item de la page précédente ?\nL'installation ne peut pas se faire."));
      mess                   . exec();
      if(     mess.clickedButton() == OKButton){
          mess.close();
          return;
      }
      else if(mess.clickedButton() == AbButton){
          qApp-> closeAllWindows();
          return;
      }
  
  }
   
  if(2 ==pageFinale){
   

  QFile        alarmesText    (g_path+"/Programmes/drtux/bin/Ressources/Menus/Alarmes/definition.txt");
  QFile        alarmesPng     (g_path+"/Programmes/drtux/bin/Ressources/Menus/Alarmes/alarmes.png");
  QFile        lectureText    (g_path+"/Programmes/drtux/bin/Ressources/Menus/LectureAlertes/definition.txt");
  QFile        lecturePng     (g_path+"/Programmes/drtux/bin/Ressources/Menus/LectureAlertes/lecture.png");

  if(alarmesText.exists() == false){

      texte                =  trUtf8("Erreur: Alarmes ne s'est pas installé correctement.");
      texteHtml            =  "<html><body><font size = 6 color = ""red"">"+texte+"</font></body></html>";
               
      label                -> setText(texteHtml);
      label                -> setWordWrap(true);
     
  }
  else if(alarmesPng.exists() == false){
      texte                =  trUtf8("Erreur: Alarmes ne s'est pas installé correctement.");
      texteHtml            =  "<html><body><font size = 6 color = ""red"">"+texte+"</font></body></html>";
      label                -> setText(texteHtml);
      label                -> setWordWrap(true);
  }
    else if(lectureText.exists() == false){
      texte                =  trUtf8("Erreur: LectureAlertes ne s'est pas installé correctement.");
      texteHtml            =  "<html><body><font size = 6 color = ""red"">"+texte+"</font></body></html>";
      label                -> setText(texteHtml);
      label                -> setWordWrap(true);
  }
    else if(lecturePng.exists() == false){
      texte                =  trUtf8("Erreur: LectureAlertes ne s'est pas installé correctement.");
      texteHtml            =  "<html><body><font size = 6 color = ""red"">"+texte+"</font></body></html>";
      label                -> setText(texteHtml);
      label                -> setWordWrap(true);
  }
  else{

      texte                 = trUtf8("Félicitations pour votre installation.<br/>Veuillez relancer Manager.");
      texteHtml             = "<html><body><font size = 6 color = ""red"">"+texte+"</font></body></html>";
      label                -> setText(texteHtml);
      label                -> setWordWrap(true);
      
  }
  }
 
}

void page2::instalTables(){
   qDebug() << "dans installtables";
   if(CreateConnection() ==false){
   qDebug() << "dans installtables ensuite";
      if(remplirPointIni() == false){
          return;
      }
      
      QMessageBox mess;
      QPushButton *OKButton  = mess . addButton(tr("Ok"),QMessageBox::AcceptRole);
      QPushButton *AbButton  = mess . addButton(trUtf8("Quitter"),QMessageBox::RejectRole);
      mess                   . setText(trUtf8("les fichiers .ini ont été renseignés avec votre mot de passe Mysql,"
                                              "veuillez relancer le setup arpès la fermeture automatique."));
      mess                   . exec();
      if(     mess.clickedButton() == OKButton){
          qApp-> closeAllWindows();
          return;
      }
      else if(mess.clickedButton() == AbButton){
          qApp-> closeAllWindows();
          return;
      }
  }
   QSqlDatabase db = QSqlDatabase::database();
   QSqlQuery query;
   query.exec("SELECT * FROM Alarmes");
   QSqlRecord record = query.record();
   int count         = record.count();
   if(count > 0 && count< 9){
     QSqlQuery alter1;
     QString   req1         = "ALTER TABLE Alarmes CHANGE Alarm_IDDos Alarm_IDDos VARCHAR( 36 ) CHARACTER SET utf8  COLLATE utf8_unicode_ci NULL";
               alter1       . exec(req1);
     QSqlQuery alter2;
     QString   req2         = "ALTER TABLE Alarmes CHANGE Alarm_valid Alarm_valid TINYINT( 1 ) NULL";
               alter2       . exec(req2);
     QSqlQuery alter3;
     QString   req3         = "ALTER TABLE Alarmes ADD Alarm_utilisateur  varchar(30) COLLATE utf8_unicode_ci NULL AFTER Alarm_valid";
               alter3       . exec(req3);
     QSqlQuery alter4;
     QString   req4         = "ALTER TABLE Alarmes CHANGE Alarm_Date Alarm_Date datetime NULL";
               alter4       . exec(req4);
     QSqlQuery alter5;
     QString   req5         = "ALTER TABLE Alarmes CHANGE Alarm_AlarmDate Alarm_AlarmDate datetime NULL";
               alter5       . exec(req5);
     
   }
   else{
     QStringList listeAlarmes;
     QString strList        = "";
     QFile fileAlarmesIni(g_pathabsolu+"/dump_alarmes.sql");
     if(!fileAlarmesIni.open(QIODevice::ReadOnly)){
        QMessageBox::warning(0,QObject::tr("Erreur"),QObject::trUtf8("dump_alarmes.sql non trouvé."),QMessageBox::Ok);
        }
    QTextStream streamAlarmes(&fileAlarmesIni);
    while(!streamAlarmes.atEnd()){
        QString ligneAlarmes = streamAlarmes.readLine();
        strList           += ligneAlarmes;
            if (ligneAlarmes.endsWith(";") && (ligneAlarmes.endsWith("*//;")) == false ){
                listeAlarmes       << strList;
                strList          = "";
                }
        }

    for(int i = 0; i < listeAlarmes.size() ; i++){
        QSqlQuery query(db);
        query.exec(listeAlarmes[i]);
    }
    QSqlQuery queryCharsetUtf8(db);
    QString   reqUtf8         = "ALTER TABLE Alarmes CONVERT TO CHARACTER SET utf8;";
              queryCharsetUtf8.exec(reqUtf8);

   }

}

bool page2::remplirPointIni(){
  QString host1             = "";
  QString util1             = "";
  QString Mdp1              = "";
  QString host2             = "";
  QString util2             = "";
  QString Mdp2              = "";
  qDebug() << "avant dialog";
  mdp *dialog               = new mdp(this);
  if(dialog -> exec()      == QDialog::Accepted){
      host2                 = dialog->lineEdit_3->text();
      util2                 = dialog->lineEdit_2->text();
      Mdp2                  = dialog->lineEdit->text();
      qDebug () << "host="+host2+" util="+util2+" mdp="+Mdp2;
  }
  else{
      QMessageBox::critical(0,trUtf8("Fatal"),trUtf8("Connection à Alarmes utilisateur.ini impossible.\n Fermeture."),QMessageBox::Ok);
      emit QApplication::closeAllWindows();
      return false;
  }
  delete dialog;
  QStringList listAl;
  QStringList listLect;
  QFile fileAl  (g_path+"/Programmes/pensebetux/Alarmes/bin/utilisateur.ini");
  QFile fileLect(g_path+"/Programmes/pensebetux/lecture_table_alarmes/bin/utilisateur.ini");
  if(!fileAl.open(QIODevice::ReadWrite|QIODevice::Text)){
      QMessageBox::critical(0,trUtf8("Fatal"),trUtf8("Connection à Alarmes utilisateur.ini impossible."),QMessageBox::Ok);
   }
  if(!fileLect.open(QIODevice::ReadWrite|QIODevice::Text)){
      QMessageBox::critical(0,trUtf8("Fatal"),trUtf8("Connection à Lecture  utilisateur.ini impossible."),QMessageBox::Ok);
   }
  QTextStream streamAl(&fileAl);
  while(!streamAl.atEnd()){
      QString line        = streamAl.readLine();
              listAl     << line;
  }
  QString     lineHost    = listAl[0];
  QString     lineUtil    = listAl[1];
  QString     lineMdp     = listAl[2];
  QStringList listHost    = lineHost.split("=");
  QStringList listUtil    = lineUtil.split("=");
  QStringList listMdp     = lineMdp.split("=");
  host1                   = listHost[0];
  util1                   = listUtil[0];
  Mdp1                    = listMdp[0];
  QTextStream streamLect(&fileLect);
  while(!streamLect.atEnd()){
      QString line        = streamLect.readLine();
              listLect     << line;
  }
  listAl                . replaceInStrings(lineHost,host1+"="+host2);
  listAl                . replaceInStrings(lineUtil,util1+"="+util2);
  listAl                . replaceInStrings(lineMdp,Mdp1+"="+Mdp2);

  listLect              . replaceInStrings(lineHost,host1+"="+host2);
  listLect              . replaceInStrings(lineUtil,util1+"="+util2);
  listLect              . replaceInStrings(lineMdp,Mdp1+"="+Mdp2);
  
  
  fileAl.close();
  fileLect.close();
  QFile fileAl2  (g_path+"/Programmes/pensebetux/Alarmes/bin/utilisateur.ini");
  QFile fileLect2(g_path+"/Programmes/pensebetux/lecture_table_alarmes/bin/utilisateur.ini");
  if(!fileAl2.open(QIODevice::ReadWrite|QIODevice::Text)){
      QMessageBox::critical(0,trUtf8("Fatal"),trUtf8("Connection à Alarmes utilisateur.ini impossible."),QMessageBox::Ok);
   }
  if(!fileLect2.open(QIODevice::ReadWrite|QIODevice::Text)){
      QMessageBox::critical(0,trUtf8("Fatal"),trUtf8("Connection à Lecture  utilisateur.ini impossible."),QMessageBox::Ok);
   }
  QTextStream streamAl2(&fileAl2);
  for(int i=0;i<listAl.size();i++){
      streamAl2 << listAl[i]+"\n";
  }
  QTextStream streamLect2(&fileLect2);
  for(int i = 0;i < listLect.size();i++){
      streamLect2 << listLect[i]+"\n";
  }
  fileAl2.close();
  fileLect2.close();
  return true;
}

