/****************************************************************************
** ui.h extension file, included from the uic-generated form implementation.
**
** If you want to add, delete, or rename functions or slots, use
** Qt Designer to update this file, preserving your code.
**
** You should not define a constructor or destructor in this file.
** Instead, write your code in functions called init() and destroy().
** These will automatically be called by the form's constructor and
** destructor.
*****************************************************************************/

//---------------------------------------- init ------------------------------------------------
void Dlg_Patch::init()
{m_pCTheraBase   = 0;
 m_pCMoteurBase  = 0;
 m_pCMedicaBase  = 0;
 m_AutoTerminate = 0;
 m_Test          = "";

 textEdit_infos->hide();
 //...................... recuperer action ....................................................
 m_Action        = "";
 if (qApp->argc()>=2)  m_Action = QString(qApp->argv()[1]);

 //...................... recuperer chemin de l'application ....................................
 QFileInfo qfi(qApp->argv()[0]);                    //qApp->argv()[i]
 m_PathAppli    = CGestIni::Construct_PathBin_Module("mise_a_jour",QFileInfo (qApp->argv()[0]).dirPath (true));
 m_PatchParam   = "";
 m_PathDrTux    = CGestIni::Construct_PathBin_Module("drtux", QFileInfo (qApp->argv()[0]).dirPath (true));
 textLabelInfo->setText(tr("Bienvenue sur la mise à jour de MedinTux "));
 setIcon( m_PathAppli + "Ressources/Patch.png" );
 if (m_Action.left(5).lower() == "test ")         // ATTENTION il y a aussi 'Tester base' donc comparer 'test ' avec l'espace separateur
    {m_Action = m_Action.mid(4).stripWhiteSpace();
     m_Test   = "ok";
     textEdit_infos->show();
    }
 else
    {pushButtonOk->hide();
     pushButtonAnnuler->hide();
    }
 QString val;
 QString VersionTxt = CGestIni::Construct_Name_File_Ini( "mise_a_jour",QFileInfo (qApp->argv()[0]).dirPath (true),"Ressources/Version.txt");
 // QString log;
 // CMoteurBase::Param_UpdateFromDisk(m_PathAppli + "Ressources/Log.txt", log);
 // log += QString (" Action :" ) + m_Action + "\n";
 // CMoteurBase::Param_UpdateToDisk(m_PathAppli + "Ressources/Log.txt", log);
 //................ action selon param d'entrée ..............................
 if (m_Action == "Do Update")
    {
     if (InitCMoteurBase()&&InitCMedicaBase())
       {if ( m_Test   != "ok" )
           {QTimer::singleShot( 2000, this, SLOT(pushButtonOk_clicked()) );
            m_AutoTerminate = 2;              // interface non affihée
           }
        else
           {m_AutoTerminate = 1;              // on affiche l'interface
           }
            // interface affichée
        //CMoteurBase::Param_UpdateToDisk(m_PathAppli + "Ressources/Version.txt", "ok");
        CMoteurBase::Param_UpdateToDisk(VersionTxt, "ok");
        //m_pCMoteurBase->GotoDebug();
      }
     else
       {textLabelInfo->setText(tr("Les Bases de données n'ont pas pu être "
                                  "initialisées correctement.<br>"
                                  "Veuillez vérifier leur installation et à "
                                  " éventuellement reinstaller toutes les bases de données."
                                  ) );
        //pushButtonAnnuler->show();
        //CMoteurBase::Param_UpdateToDisk(m_PathAppli + "Ressources/Version.txt", "Erreur 00");
        CMoteurBase::Param_UpdateToDisk(VersionTxt, "Erreur 00");
        Sortir();
       }
    }
 else if (m_Action=="Get Version")
    {QTimer::singleShot( 400, this, SLOT(Sortir()) );
     m_AutoTerminate = 2;   // interface non affichée
     val="0.01";
     CMoteurBase::Param_UpdateToDisk(VersionTxt, val);
     if (InitCMoteurBase())
        { m_pCMoteurBase->GetMedinTuxVersion(val);
        }
     else
        {val = "0.00";
        }
     textLabelInfo->setText(tr("Bienvenue sur la mise à jour de MedinTux ") + val);
     CMoteurBase::Param_UpdateToDisk(VersionTxt, val);
    }
    else if (m_Action=="Set Datasemp Version")
        {QTimer::singleShot( 400, this, SLOT(Sortir()) );
        m_AutoTerminate = 2;  // interface non affichée
        val = qApp->argv()[2];
        if (InitCMedicaBase())
                {SetDatasempIndexVersion(val);
        }
        textLabelInfo->setText(tr("Bienvenue sur la mise à jour de MedinTux ") + val);
        CMoteurBase::Param_UpdateToDisk(VersionTxt, val);
        }
    else if (m_Action=="Get Datasemp Version")
        {QTimer::singleShot( 400, this, SLOT(Sortir()) );
        m_AutoTerminate = 2;  // interface non affichée
        val = "0.00";
        if (InitCMedicaBase())
                {val = GetDatasempIndexVersion();
        }
        textLabelInfo->setText(tr("Bienvenue sur la mise à jour de MedinTux ") + val);
        CMoteurBase::Param_UpdateToDisk(VersionTxt, val);
        }
    else if (m_Action=="Tester base")
       {QTimer::singleShot( 400, this, SLOT(Sortir()) );
        m_AutoTerminate = 2;  // interface non affichée
        val = "0.00";
        testBase(val);
        QString pass = qApp->argv()[5];
        if (pass=="_=OO=_") pass = "";
        textLabelInfo->setText(tr("Connexion à la base : ") +
                               qApp->argv()[2] +"::" +      // driver
                               qApp->argv()[3] +"::" +      // base
                               qApp->argv()[4] +"::" +      // user
                               pass            +"::" +      // pass
                               qApp->argv()[6] +"::" +      // host
                               val);
        CMoteurBase::Param_UpdateToDisk(VersionTxt, val);
        }
    else
        {if (InitCMoteurBase()&&InitCMedicaBase())
                {pushButtonAnnuler->show();
                pushButtonOk->show();
                }
        else
                {textLabelInfo->setText(tr("Les Bases de données n'ont pas pu être "
                                  "initialisées correctement.<br>"
                                  "Veuillez vérifier leur installation et à "
                                  "éventuellement toutes les reinstaller."
                                  ) );
                pushButtonAnnuler->show();
              }
        }
  //................... infos des paramètres si debug mode ..........................
  if (m_Test   == "ok")
     {QString info;
      for (int i = 0; i<qApp->argc(); ++i)
          {info += tr("\r\nArgument ") + QString::number(i) + " = \t\t" +qApp->argv()[i];
          }
      info += tr("\r\nm_Action ") + m_Action;
      textEdit_infos->setText(info);
      textLabelInfo->setText(tr("Bienvenue sur la mise à jour de MedinTux (")+m_Action + ") " + QString::number(m_AutoTerminate));
    }
 else
    {textLabelInfo->setText(tr("Bienvenue sur la mise à jour de MedinTux"));
    }
}

//-------------------------------------- testBase ---------------------------------------------------
int Dlg_Patch::testBase(QString &val)
{
 QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( qApp->argv()[2] );
 if (defaultDB==0)
    {val = tr("ERROR database driver not exist");
     return 0;
    }
 QString pass = qApp->argv()[5];
 if (pass=="_=OO=_") pass = "";

 defaultDB->setDatabaseName( qApp->argv()[3] );    // base name
 defaultDB->setUserName(     qApp->argv()[4] );    // connexion name
 defaultDB->setPassword(     pass );               // password
 defaultDB->setHostName(     qApp->argv()[6] );    // hostname (distant or local)

 if ( defaultDB->open() )
    {val = "OK";
     defaultDB->close();
     return 1;
    }
 val = "ERROR";
 return 0;
}

//-------------------------------------- InitCMoteurBase -----------------------------------------
int Dlg_Patch::InitCMoteurBase()
{   QString qstr       = "";
    QString val1       = "";
    QString val2       = "";
    QString val3       = "";
    QString val4       = "";
    QString qstr2      = "";

 //................ recuperer param de connexion de DrTux.ini .................................
 //m_PathDrTuxIni = QDir::cleanDirPath ( m_PathAppli + "../../drtux/bin/DrTux.ini" );
 m_PathDrTuxIni = CGestIni::Construct_Name_File_Ini( "drtux",QFileInfo (qApp->argv()[0]).dirPath (true),"");
 CMoteurBase::Param_UpdateFromDisk( m_PathDrTuxIni , m_PatchParam );
 CMoteurBase::Param_UpdateFromDisk( m_PathAppli + "Ressources/DataBase.cfg" , m_BaseCfg );
 //................................lire les parametres de connexion ............................
 if (CMoteurBase::Param_ReadParam( m_PatchParam, "Connexion", "Parametres", &val1, &val2, &val3, &val4, &qstr2) !=0 )  // zero = pas d'erreur
    { val1     = "QMYSQL3";
      val2     = "DrTuxTest";
      val3     = "root";
      val4     = "";
      qstr2    = "";
    }
 //....................... ouvrir et initialiser le moteur de base de données ....................................
 m_pCMoteurBase = new CMoteurBase(val1 ,                   // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                                  val2,                    // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                                  val3,                    // = "root"       user
                                  val4,                    // = ""           password
                                  qstr2,                   // = "localhost"  hostname
                                  m_BaseCfg,
                                  &qstr);
 if (m_pCMoteurBase==0)        {textLabelInfo->setText(tr("Echec de la connexion à la base : ") + val2);
                                pushButtonOk->hide();
                                return 0;
                               }
 if (m_pCMoteurBase->m_DataBase ==0)   {textLabelInfo->setText(tr("Echec de la connexion à la base : ") + val2);
                                        delete m_pCMoteurBase; m_pCMoteurBase=0;
                                        pushButtonOk->hide();
                                        return 0;
                                       }
 m_pCMoteurBase->GetMedinTuxVersion(val1);
 setCaption(tr("MedinTux version : ")+val1);
 return 1;
}

//-------------------------------------- InitCMedicaBase -----------------------------------------
int Dlg_Patch::InitCMedicaBase()
{//......................... va falloir aussi avoir la base medicamenteuse ........................................

 QString MedicaBaseIni = CGestIni::Construct_Name_File_Ini("drtux",QFileInfo (qApp->argv()[0]).dirPath (true),"MedicaBase.ini");
 QString MedicaBaseCfg = CGestIni::Construct_Name_File_Ini("drtux",QFileInfo (qApp->argv()[0]).dirPath (true),"MedicaBase.cfg");

 m_pCMedicaBase = new CMedicaBase(MedicaBaseIni ,MedicaBaseCfg
                                 );
 if (m_pCMedicaBase->m_MedicaBase==0) {delete m_pCMedicaBase; m_pCMedicaBase=0; return 0;}
 return 1;
}
//---------------------------------------- Sortir ------------------------------------------------
void Dlg_Patch::Sortir()
{accept();
}

//---------------------------------------- destroy ------------------------------------------------
void Dlg_Patch::destroy()
{if (m_pCTheraBase ) delete m_pCTheraBase;
 if (m_pCMoteurBase) delete m_pCMoteurBase;
 if (m_pCMedicaBase) delete m_pCMedicaBase;
}

//---------------------------------------- CopieDataBaseCfg ------------------------------------------------
void Dlg_Patch::CopieDataBaseCfg(const QString &fileName)
{//...................... copier les nouveaux fichiers de configuration ................................................
     //                       pour que la base de donnée puisse etre initialisée
     QString dst    =  "";
     QString src    = m_PathAppli + "Ressources/" + fileName;

     dst    = CGestIni::Construct_PathBin_Module("drtux",QFileInfo (qApp->argv()[0]).dirPath (true));
     CHtmlTools::Copy_File(src, dst);

     dst    = CGestIni::Construct_PathBin_Module("Manager",QFileInfo (qApp->argv()[0]).dirPath (true));
     CHtmlTools::Copy_File(src, dst);

     dst    = CGestIni::Construct_PathBin_Module("gest_user",QFileInfo (qApp->argv()[0]).dirPath (true));
     CHtmlTools::Copy_File(src, dst);

}


//---------------------------------------- pushButtonOk_clicked ------------------------------------------------
void Dlg_Patch::pushButtonOk_clicked()
{
 QString val;
 //.................. renommer correctement les tables .....................................
 //                   (ces foutus dump de windows ne respectent pas la casse)
 m_pCMoteurBase->RenameTableWhithCorrectName();
 //...................................................................... V0 ==> V1 .......................................
 if (m_pCMoteurBase->GetMedinTuxVersion(val)==0)
    {QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
     textLabelInfo->setText(tr("MedinTux version : 0 vers version 1.00 en cours ..."));
     //...................... copier les nouveaux fichiers de configuration ................................................
     //                       pour que la base de donnée puisse etre initialisée
     CopieDataBaseCfg("DataBase.cfg");
     //.................. créer la table des versions.............................................
     if (m_pCMoteurBase->m_DataBase->isOpen()==FALSE && m_pCMoteurBase->m_DataBase->open()==FALSE)  return;
     QSqlQuery query(QString::null, m_pCMoteurBase->m_DataBase);

     //.................. créer la table de version .............................................
     query.exec("CREATE TABLE IF NOT EXISTS version ("
                "`NumVers` varchar(32) NOT NULL default ''"
                ") TYPE=MyISAM;");
     //.................. créer les nouveaux champs.............................................
     query.exec("INSERT INTO `version` VALUES (\"1.00\");");
     query.exec("ALTER TABLE `RubriquesBlobs` ADD `RbDate_IDDos` varchar(36);");
     query.exec("ALTER TABLE `RubriquesBlobs` ADD INDEX `RbDate_BlobsIDDosIndex`(`RbDate_IDDos`);");
     query.exec("ALTER TABLE `RubriquesHead`  ADD `RbDate_RefBlobs_PrimKey` bigint;");
     m_pCMoteurBase->ConvertToNew(textLabelInfo, progressBar);
     m_pCMoteurBase->m_DataBase->close();

     m_pCMoteurBase->GetMedinTuxVersion(val);
     setCaption(tr("MedinTux version : ")+val);

     //................... créer le numéro de version Datasemp de MedicaBase ..............................
     //                    sert à verifier si l'index de MedicaBase est cohérent avec Datasemp
     if (m_pCMedicaBase->m_DataGet_Base->isOpen()==FALSE && m_pCMedicaBase->m_DataGet_Base->open()==FALSE)  return;

     QSqlQuery query_m(QString::null, m_pCMedicaBase->m_DataGet_Base);
     query_m.exec("CREATE TABLE IF NOT EXISTS `version` ("
                  "`DatasempVersion` varchar(32) NOT NULL default ''"
                  ") TYPE=MyISAM;"
                 );
     m_pCMedicaBase->OutSQL_error( query_m);
     query_m.exec("INSERT INTO `version` VALUES (\"110B02.2\");");
     m_pCMedicaBase->m_DataGet_Base->close();
     QApplication::restoreOverrideCursor();
    }
 //...................................................................... V1 ==> V1.2 .......................................
 if ( m_pCMoteurBase->GetMedinTuxVersion(val) < 1.20 ) /////////////////////////////////////////////////////////////////// V 1.20 //////////////////////////////////
    {QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
     textLabelInfo->setText(tr("MedinTux version : 1 vers version 1.2 en cours ..."));
     //..................................Ouverture base patient ........................................
     if ( ! (m_pCMoteurBase->m_DataBase->isOpen()==FALSE && m_pCMoteurBase->m_DataBase->open()==FALSE))
        {QSqlQuery query(QString::null, m_pCMoteurBase->m_DataBase);
         query.exec("INSERT INTO `version` VALUES (\"1.20\");");
         //   UPDATE UserDoc SET `NameDoc` = 'Parametres' WHERE `NameDoc`= 'Paramètres';
         query.exec(QString(" UPDATE ") + m_pCMoteurBase->m_USER_DATA_TBL_NAME +" SET `" +
                    m_pCMoteurBase->m_USER_DATA_NAMEDOC + "` = 'Parametres' WHERE `"     +  m_pCMoteurBase->m_USER_DATA_NAMEDOC + "` = 'Param�res' ;");
         query.exec(QString(" UPDATE ") + m_pCMoteurBase->m_USER_DATA_TBL_NAME +" SET `" +
                    m_pCMoteurBase->m_USER_DATA_NAMEDOC + "` = 'Parametres' WHERE `"     +  m_pCMoteurBase->m_USER_DATA_NAMEDOC + "` = 'Paramètres' ;");

         m_pCMoteurBase->m_DataBase->close();
        }

     //..................................Ouverture  base therapeutique GET........................................
     if (m_pCMedicaBase->m_DataBaseSrce && ! (m_pCMedicaBase->m_DataBaseSrce->isOpen()==FALSE && m_pCMedicaBase->m_DataBaseSrce->open()==FALSE))
        {QSqlQuery query(QString::null, m_pCMedicaBase->m_DataBaseSrce);
         query.exec("ALTER TABLE `Posologies`       MODIFY  `Divers` varchar(128);");
         query.exec("ALTER TABLE `Posologies_Perso` MODIFY  `Divers` varchar(128);");

         m_pCMedicaBase->m_DataBaseSrce->close();
        }

     //..................................Ouverture  base therapeutique DATASEMP........................................
     if (m_pCMedicaBase->m_DataGet_Base && ! (m_pCMedicaBase->m_DataGet_Base->isOpen()==FALSE && m_pCMedicaBase->m_DataGet_Base->open()==FALSE))
        {QSqlQuery query(QString::null, m_pCMedicaBase->m_DataGet_Base);
         query.exec("ALTER TABLE `Posologies`       MODIFY  `Divers` varchar(128);");
         query.exec("ALTER TABLE `Posologies_Perso` MODIFY  `Divers` varchar(128);");

         m_pCMedicaBase->m_DataGet_Base->close();
        }
     QApplication::restoreOverrideCursor();
    }
 if ( m_pCMoteurBase->GetMedinTuxVersion(val) < 1.25 ) /////////////////////////////////////////////////////////////////// V 1.25 //////////////////////////////////
    {QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
     textLabelInfo->setText(tr("MedinTux version : 1 vers version 1.25 en cours ..."));
     //..................................Ouverture base patient ........................................
     if ( ! (m_pCMoteurBase->m_DataBase->isOpen()==FALSE && m_pCMoteurBase->m_DataBase->open()==FALSE))
        {QSqlQuery query(QString::null, m_pCMoteurBase->m_DataBase);
         query.exec("INSERT INTO `version` VALUES (\"1.25\");");
         query.exec("ALTER TABLE `Personnes`        MODIFY  `Droits` varchar(200);");
         //......................... rajout du sexe dans Personnes .........................................................
         //   UPDATE UserDoc SET `NameDoc` = 'Parametres' WHERE `NameDoc`= 'Paramètres';
         //   ALTER TABLE 'Personnes'  ADD 'Sexe' varchar(2) default ''  AFTER 'Droits'
         QString requete = QString(" ALTER TABLE ") + m_pCMoteurBase->m_USER_IDENT_TBL_NAME + " ADD `Sexe` varchar(2) default '' AFTER `"     +  m_pCMoteurBase->m_USER_IDENT_DROITS + "` ;";
         query.exec(requete);
         //......................... rajout du sexe dans Personnes .........................................................
         requete = QString(" ALTER TABLE ") + m_pCMoteurBase->m_USER_IDENT_TBL_NAME + " ADD `" +
                           m_pCMoteurBase->m_USER_IDENT_SEXE + "` varchar(2) default '' AFTER `"     +  m_pCMoteurBase->m_USER_IDENT_DROITS + "` ;";

         //................................. rajout des champs Utilisateur signataire........................................
         query.exec(requete);
         query.exec("ALTER TABLE `Verrous` ADD  `SignUserName` varchar(32) default '' AFTER `UserName`;");
         query.exec("ALTER TABLE `RubriquesHead` ADD  `RbDate_CreateSignUser` varchar(32) default '' AFTER `RbDate_CreateUser`;");
         //................................. création de la table de gestion des utilisateurs signataires ....................
         requete = QString(" CREATE TABLE `") + m_pCMoteurBase->m_USER_PERMS_TBL_NAME + "` (  `" +
                    m_pCMoteurBase->m_USER_PERMS_PK + "` bigint(20) unsigned NOT NULL auto_increment,  `" +
                    m_pCMoteurBase->m_USER_PERMS_SIGN_GUID+"` varchar(36) default NULL,  `" +
                    m_pCMoteurBase->m_USER_PERMS_FRIEND_GUID+"` varchar(36) default NULL,  `" +
                    m_pCMoteurBase->m_USER_PERMS_FRIEND_DROITS+"` varchar(200) default NULL, `" +
                    m_pCMoteurBase->m_USER_PERMS_FRIEND_BLOBS+"` BLOB ,  PRIMARY KEY(`"+m_pCMoteurBase->m_USER_PERMS_PK+"`),"+
                    "  KEY `user_perms_Index` (`"+m_pCMoteurBase->m_USER_PERMS_FRIEND_GUID+"`) )TYPE=MyISAM;";

         query.exec(requete);
         //..................... rajouter tous les droits aux utilisateurs afin que MedinTux fonctionne comme avant ................................................
         AddDroitsToAllUser(query, "-sgn-orv-orc-orp-orr-bmc-ccc-acc-cic-lac-obv-obc-obp-glc-gld-etc-ata-atv-atc-ttv-ttc-tvv-tvc", 1);   // 1 pour table  'Personnes'
         //.................................. copier les bonnes définitions de tables tenant compte des rajouts et création ..............
         CopieDataBaseCfg("DataBase.cfg");
         //................................... modifier la table  des
         m_pCMoteurBase->m_DataBase->close();
        }
     QApplication::restoreOverrideCursor();
    }
 if ( m_pCMoteurBase->GetMedinTuxVersion(val) < 1.26 ) /////////////////////////////////////////////////////////////////// V 1.26 //////////////////////////////////
    {QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
     textLabelInfo->setText(tr("MedinTux version : 1 vers version 1.26 en cours ..."));
     //..................................Ouverture base patient ........................................
     if ( ! (m_pCMoteurBase->m_DataBase->isOpen()==FALSE && m_pCMoteurBase->m_DataBase->open()==FALSE))
        {QSqlQuery query(QString::null, m_pCMoteurBase->m_DataBase);
         //......................... placer le numéro de version .........................................................
         query.exec("INSERT INTO `version` VALUES (\"1.26\");");
         //......................... Ralonger les droits .........................................................
         query.exec("ALTER TABLE `Personnes`        MODIFY  `Droits` varchar(200);");
         query.exec("ALTER TABLE `" + m_pCMoteurBase->m_USER_PERMS_TBL_NAME +"` MODIFY  `" + m_pCMoteurBase->m_USER_PERMS_FRIEND_DROITS + "` varchar(200);");
         //..................... rajouter les droit -agc-agv-idv-idc-idg aux utilisateurs ................................................
         AddDroitsToAllUser(query, "-agc-agv-idv-idc-idg",3);                                       // 3 pour table  'Personnes' et 'perms_user'
         m_pCMoteurBase->m_DataBase->close();
        }
     //.................................... copier le fichier de config pour modifier la base  des medoc et compte des Durees conseillees et de la secabilite ...........................
     QString dst    =  CGestIni::Construct_PathBin_Module("drtux",QFileInfo (qApp->argv()[0]).dirPath (true));
     QString src    =  m_PathAppli + "Ressources/Vers-1.26/MedicaBase.cfg";
     CHtmlTools::Copy_File(src, dst);
     //..................................... ouvrir les bases therapeutiques ................................................................
     if (m_pCTheraBase==0) m_pCTheraBase   = new (CTheraBase);
     if (m_pCTheraBase && m_pCTheraBase->m_AllIsOk)
        {if (m_pCTheraBase->m_DatasempIndexBase->isOpen()==TRUE && m_pCTheraBase->m_DatasempIndexBase->open()==TRUE)
            {QSqlQuery queryVidal(QString::null, m_pCTheraBase->m_DatasempIndexBase);
             queryVidal.exec("ALTER TABLE `Posologies` ADD  `Pendant` float default NULL AFTER `Divers`;");
             queryVidal.exec("ALTER TABLE `Posologies_Perso` ADD  `Pendant` float default NULL AFTER `Divers`;");
             queryVidal.exec("ALTER TABLE `Posologies` ADD  `Secabilite` char(1) default '' AFTER `Pendant`;");
             queryVidal.exec("ALTER TABLE `Posologies_Perso` ADD  `Secabilite` char(1) default '' AFTER `Pendant`;");
             m_pCTheraBase->m_DatasempIndexBase->close();
            }
         if (m_pCTheraBase->m_DataIndexGet_Base->isOpen()==TRUE && m_pCTheraBase->m_DataIndexGet_Base->open()==TRUE)
            {QSqlQuery   queryGet(QString::null, m_pCTheraBase->m_DataIndexGet_Base);
             queryGet.exec("ALTER TABLE `Posologies` ADD  `Pendant` float default NULL AFTER `Divers`;");
             queryGet.exec("ALTER TABLE `Posologies_Perso` ADD  `Pendant` float default NULL AFTER `Divers`;");
             queryGet.exec("ALTER TABLE `Posologies` ADD  `Secabilite` char(1) default '' AFTER `Pendant`;");
             queryGet.exec("ALTER TABLE `Posologies_Perso` ADD  `Secabilite` char(1) default '' AFTER `Pendant`;");
             m_pCTheraBase->m_DataIndexGet_Base->close();
            }
        }
     QApplication::restoreOverrideCursor();
    }
 if ( m_pCMoteurBase->GetMedinTuxVersion(val) < 2 || m_Test=="ok") /////////////////////////////////////////////////////////////////// V 2.00 //////////////////////////////////
    {QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
     textLabelInfo->setText(tr("MedinTux vers version 2 en cours ..."));
     QString     v;

     //..................................Ouverture base patient ........................................
     if ( ! (m_pCMoteurBase->m_DataBase->isOpen()==FALSE && m_pCMoteurBase->m_DataBase->open()==FALSE))
        {QSqlQuery query(QString::null, m_pCMoteurBase->m_DataBase);
         //......................... placer le numéro de version .........................................................
         query.exec("INSERT INTO `version` VALUES (\"2.00\");");
         //......................... Ralonger les droits .........................................................
         query.exec("ALTER TABLE `RubriquesHead`  ADD     `RbDate_SubTypeRub` varchar(50) default NULL AFTER `RbDate_NomDate`;");
         query.exec("ALTER TABLE `RubriquesHead`  MODIFY  `RbDate_NomDate` varchar(50);");
         query.exec("ALTER TABLE `RubriquesBlobs` MODIFY  `RbDate_DataRub` longblob;");

         //..................... rajouter les droit -doc-obc-orc aux utilisateurs ................................................
         AddDroitsToAllUser(query, "-doc-obc-orc",3);                                       // 3 pour table  'Personnes' et 'perms_user'
         //........................... creer les données utilisateur (parametres fenetres et documents type) de la rubrique Documents .....................................
         QStringList qstringList;
         QString     text;
         QString     pk_record;
         QString     us_pk;
         QString     doc_pk;

         QString      str = "=={{<html><head><meta name=\"qrichtext\" content=\"1\" /></head><body style=\"font-size:10pt;font-family:Sans\">\n"
                            "<p align=\"center\"><span style=\"font-style:italic;font-size:8pt\">Imprimé en date du : {{dd-MM-yyyy}} document "
                            "provenant du dossier de {{TITRE PATIENT}} {{NOM PRENOM PATIENT}}</span></p>\n</body></html>\n}}==/r/n=={{}}==/r/n";

         QString requete("SELECT ");
                 requete       += m_pCMoteurBase->m_USER_IDENT_LOGIN + " FROM " + m_pCMoteurBase->m_USER_IDENT_TBL_NAME
                               +  " WHERE " + m_pCMoteurBase->m_USER_IDENT_DROITS 
                               +  " LIKE '%-sgn%' ORDER BY " + m_pCMoteurBase->m_USER_IDENT_LOGIN;
         query.exec(requete);
         if (query.isActive())
            {qstringList.clear();
             while (query.next())  qstringList.append(query.value(0).toString() );                    // on a la liste des utilisateurs signataires
            } //endif (pSqlQuery && pSqlQuery->isActive())
         m_pCMoteurBase->m_DataBase->close();
         QStringList::Iterator it;
         for (  it = qstringList.begin(); it != qstringList.end(); ++it )        // pour tous des utilisateurs signataires ajouter aux parametres les elements
             {text = m_pCMoteurBase->GetUserDocument(*it,
                                                     tr("Parametres"),
                                                     TYP_PARAM,        // TYP_ORDONNANCE 2  TYP_CERTIFICAT 3 TYP_OBSERVATION 4 TYP_OBSERVATION  5 TYP_PARAM
                                                     0,                // adresse de la chaine où l'on veut recuperer le pied de page
                                                     0,                // 0 par defaut (RECTO) 1 si l'on veut le DUPLICATA (que pour TYP_ORDONNANCE)
                                                     &pk_record);      // = 0;
              if (text.length())
                 {if (CMoteurBase::Param_ReadParam(text ,"Documents", "Montrer", &v) !=0)
                     {text += "\r\n\r\n[Documents]\r\n  Zoom = 10\r\n  Montrer = Normal\r\n  Position =  110 , 40 , 600 , 200\r\n";
                     } 
                  m_pCMoteurBase->UpdateUserDataFromPrimKey( pk_record, 0, 0 , 0,  text);
                 }
             }
        for (  it = qstringList.begin(); it != qstringList.end(); ++it )        // pour tous des utilisateurs signataires ajouter les documents impression
            { us_pk   = m_pCMoteurBase->GetUserPrimKey(*it);
              if (us_pk.length()) 
                 {doc_pk  = m_pCMoteurBase->IsThisUserDocExist(  TYP_CERTIFICAT, us_pk, "[Documents] * Documents" );
                  if (doc_pk.length()==0) m_pCMoteurBase->CreateUserDataFromPrimKey(TYP_CERTIFICAT, us_pk , "[Documents] * Documents",  str);
                 }
            }
     //query.exec("INSERT INTO `version` VALUES (\"2.00\");");            //             RubHead
     //query.exec("INSERT INTO `version` VALUES (\"2.00\");");            //             RubBlob
     //query.exec("INSERT INTO `version` VALUES (\"2.00\");");            //             userBlobs
     // RUBREC_LIST          rubList;
        }
     //.................................... corriger le fichier de config  drtux.ini ...........................
     QString outParam;
     QString dst;
     QString src;
     dst    =  CGestIni::Construct_PathBin_Module("drtux",QFileInfo (qApp->argv()[0]).dirPath (true));
     CMoteurBase::Param_UpdateFromDisk(dst+"drtux.ini", outParam );
     outParam.replace (tr("Mode de création dossier"),   "Mode de creation dossier");
     outParam.replace (tr("Mode de cr?tion dossier"),    "Mode de creation dossier");
     outParam.replace (tr("Mode de crï¿½tion dossier"),  "Mode de creation dossier");

     outParam.replace (tr("Accéder"),   "Acceder");
     outParam.replace (tr("Acc?er"),    "Acceder");
     outParam.replace (tr("Accï¿½er"),  "Acceder");

     outParam.replace (tr("Vérifier dossier"),   "Verifier dossier");
     outParam.replace (tr("V?ifier dossier"),    "Verifier dossier");
     outParam.replace (tr("Vï¿½ifier dossier"),  "Verifier dossier");

     outParam.replace (tr("Défaut"),   "Defaut");
     outParam.replace (tr("D?aut"),    "Defaut");
     outParam.replace (tr("Dï¿½aut"),  "Defaut");

     outParam.replace (tr("Vérification Verrou"), "Verification Verrou");
     outParam.replace (tr("V?ification Verrou"),  "Verification Verrou");
     outParam.replace (tr("Vï¿½ification Verrou"),  "Verification Verrou");

     CMoteurBase::Param_WriteParam( &outParam, "MenuContextuel", "ListDocuments", "Gestion des documents");
     CMoteurBase::Param_WriteParam( &outParam, "MenuContextuel", "ListImages",    "Gestion des images");
     if (CMoteurBase::Param_ReadParam(outParam ,"Documents", "MaxImageWidth", &v) != 0)
        {outParam += "\r\n\r\n[Documents]\r\n"
                     " Path documents = /home\r\n"
                     " MaxImageWidth = 550\r\n";
        }
     outParam.replace (tr("Masques du terrain"), "Terrain");
     outParam.replace (tr("Glossaire/Masques/"), "Glossaire/Observation/");
     CMoteurBase::Param_UpdateToDisk(dst+"drtux.ini", outParam );

     //.................................... corriger le fichier de config  Manager.ini ...........................
     dst    =  CGestIni::Construct_PathBin_Module("Manager",QFileInfo (qApp->argv()[0]).dirPath (true));
     CMoteurBase::Param_UpdateFromDisk(dst+"Manager.ini", outParam );
     outParam.replace (tr("Mode de création dossier"),   "Mode de creation dossier");
     outParam.replace (tr("Mode de cr?tion dossier"),    "Mode de creation dossier");
     outParam.replace (tr("Mode de crï¿½tion dossier"),  "Mode de creation dossier");

     outParam.replace (tr("Accéder"),   "Acceder");
     outParam.replace (tr("Acc?er"),    "Acceder");
     outParam.replace (tr("Accï¿½er"),  "Acceder");

     outParam.replace (tr("Vérifier dossier"),   "Verifier dossier");
     outParam.replace (tr("V?ifier dossier"),    "Verifier dossier");
     outParam.replace (tr("Vï¿½ifier dossier"),  "Verifier dossier");

     outParam.replace (tr("Défaut"),   "Defaut");
     outParam.replace (tr("D?aut"),    "Defaut");
     outParam.replace (tr("Dï¿½aut"),  "Defaut");

     outParam.replace (tr("Vérification Verrou"), "Verification Verrou");
     outParam.replace (tr("V?ification Verrou"),  "Verification Verrou");
     outParam.replace (tr("Vï¿½ification Verrou"),  "Verification Verrou");

     CMoteurBase::Param_WriteParam( &outParam, "MenuContextuel", "ListDocuments", "Gestion des documents");
     CMoteurBase::Param_WriteParam( &outParam, "MenuContextuel", "ListImages",    "Gestion des images");
     if (CMoteurBase::Param_ReadParam(outParam ,"Documents", "MaxImageWidth", &v) != 0)
        {outParam += "\r\n\r\n[Documents]\r\n"
                     " Path documents = /home\r\n"
                     " MaxImageWidth = 550\r\n";
        }
     outParam.replace (tr("Masques du terrain"), "Terrain");
     outParam.replace (tr("Glossaire/Masques/"), "Glossaire/Observation/");
     CMoteurBase::Param_UpdateToDisk(dst+"Manager.ini", outParam );
     //.................................... copier les bons le fichier de DataBase.cfg ...........................
     dst    =  CGestIni::Construct_PathBin_Module("drtux",QFileInfo (qApp->argv()[0]).dirPath (true));
     src    =  m_PathAppli + "Ressources/Vers-2.00/drtux/DataBase.cfg";
     CHtmlTools::Copy_File(src, dst);

     dst    =  CGestIni::Construct_PathBin_Module("Manager",QFileInfo (qApp->argv()[0]).dirPath (true));
     src    =  m_PathAppli + "Ressources/Vers-2.00/Manager/DataBase.cfg";
     CHtmlTools::Copy_File(src, dst);
     //....................................... copier les bouts de glossaires utiles ......................................
     // outParam devrait contenir le bon fichier ini
     // dst      devrait contenir le bon chemin de manager
     if (CMoteurBase::Param_ReadParam(outParam ,"Glossaire", "Path", &val) ==0)              // recuperer path du Glossaire dans le .ini
        {if ( QDir::isRelativePath ( val ) ) val  = QDir::cleanDirPath (val.prepend( dst) ); // le derelativiser
         QDir dir( val );
         dir.rename( val + "/Masques du terrain",          val + "/Terrain" );
         dir.rename( val + "/Masques",                     val + "/Observation" );
         dir.rename( val + tr("/Prescriptions médicales"), val + "/Prescription" );
         dir.mkdir ( val + "/Documents");
         src    =  m_PathAppli + "Ressources/Vers-2.00/Glossaire";
         CHtmlTools::Copy_Dir(src,  val);
        }
     //........................... creer les données utilisateur (parametres fenetres et documents type) de la rubrique Documents .....................................
     QApplication::restoreOverrideCursor();
    }
 if (m_AutoTerminate) accept();
}

//--------------------------------------- AddDroitsToAllUser ------------------------------------
void Dlg_Patch::AddDroitsToAllUser(QSqlQuery &qsqlQuery, const QString &droits, int table_type)
{        //..................... rajouter les droit -agc-agv-idv-idc-idg aux utilisateurs ................................................
         QString droitsAlreadySet = "";
         QString requete          = "SELECT  ID_PrimKey, Droits FROM Personnes where Droits like '%med%'";
    if (table_type & 1)
       { qsqlQuery.exec( requete );
         if (qsqlQuery.isActive())
            {QSqlQuery queryU (QString::null, m_pCMoteurBase->m_DataBase);
             while (qsqlQuery.next()) //                                 droits actuels            +  -sgn
                   {droitsAlreadySet  = qsqlQuery.value(1).toString();
		    droitsAlreadySet += droits;
		    if (droitsAlreadySet.left(1) != "-") droitsAlreadySet.prepend("-");
		    requete  = " UPDATE Personnes SET `Droits` = '"+ droitsAlreadySet + "' WHERE `ID_PrimKey` = '" + qsqlQuery.value(0).toString() + "' ;";
                    queryU.exec(requete);                                                        //-sgn-orv-orc-orp-orr-bmc-ccc-acc-cic-lac-obv-obc-obp-glc-gld-etc-ata-atv-atc-ttv-ttc-tvv-tvc
                   }
            } //if (pSqlQuery && pSqlQuery->isActive() && pSqlQuery->next())
       }
    if (table_type & 2)
       {
         requete          = "SELECT  PrimKey, FriendUserDroits FROM `user_perms` ;";
         qsqlQuery.exec( requete );
         if (qsqlQuery.isActive())
            {QSqlQuery queryU (QString::null, m_pCMoteurBase->m_DataBase);
             while (qsqlQuery.next()) //                                 droits actuels            +  -sgn
                   {droitsAlreadySet  = qsqlQuery.value(1).toString();
                    droitsAlreadySet += droits;
                    if (droitsAlreadySet.left(1) != "-") droitsAlreadySet.prepend("-");
                    requete  = " UPDATE user_perms SET `FriendUserDroits` = '"+ droitsAlreadySet + "' WHERE `PrimKey` = '" + qsqlQuery.value(0).toString() + "' ;";
                    queryU.exec(requete);                                                        //-sgn-orv-orc-orp-orr-bmc-ccc-acc-cic-lac-obv-obc-obp-glc-gld-etc-ata-atv-atc-ttv-ttc-tvv-tvc
                   }
            } //if (pSqlQuery && pSqlQuery->isActive() && pSqlQuery->next())
       }
}

//---------------------------------------- GetDatasempIndexVersion ------------------------------------------------
QString Dlg_Patch::GetDatasempIndexVersion()
{   return m_pCMedicaBase->Medica_GetDatasempVersion(CMedicaBase::Index);
}

//---------------------------------------- SetDatasempIndexVersion ------------------------------------------------
void Dlg_Patch::SetDatasempIndexVersion(const QString &version)
{   m_pCMedicaBase->Medica_SetDatasempVersion(QString(version), CMedicaBase::IndexAndData);
}

//---------------------------------------- RenameTableWhithCorrectName ------------------------------------------------
void Dlg_Patch::RenameTableWhithCorrectName(const QString &correct_name_table, QSqlQuery *pQSqlQuery)
{m_pCMoteurBase->RenameTableWhithCorrectName(correct_name_table, pQSqlQuery);
}

//---------------------------------------- pushButtonAnnuler_clicked ------------------------------------------------
void Dlg_Patch::pushButtonAnnuler_clicked()
{reject();
}
