/***************************************************************************
 *   Copyright (C) 2005 by Sevin Roland                                    *
 *   ro@vaio_ro                                                            *
 *                                                                         *
 *   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 "CMoteurAgenda.h"
#include "../../MedinTuxTools/CGestIni.h"
#define TR QObject::tr

//=============================================== INCLUDES ===================================================================
//=============================================== IMPLEMENTATION =====================================================
//-----------------------------------------------------  CMoteurAgenda -------------------------------------------------
CMoteurAgenda::CMoteurAgenda()
{ m_DriverName  = "";
  m_BaseName    = "";
  m_UserName    = "";
  m_PassWord    = "";
  m_HostName    = "";
  m_DataBase    = 0;

  QSqlDatabase::removeDatabase (BASE_AGENDA);
  SetDaysHeight();
  SetMinDaysHeight();
  SetSpaceBetwenDays();
}
//-----------------------------------------------------  CMoteurAgenda -------------------------------------------
CMoteurAgenda::CMoteurAgenda(const char* driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                             const char* DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                             const char* user,          // = "root"
                             const char* password,      // = ""
	                     const char* hostname,
                             const char* confFile,
                             const char* baseLabel,
			     QString*    errMess)
{ initBase   ( driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
               DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
               user,          // = "root"
               password,      // = ""
               hostname,
               confFile,
               baseLabel,
               errMess);
  SetDaysHeight();
  SetMinDaysHeight();
  SetSpaceBetwenDays();
}

//-----------------------------------------------------  initBase -------------------------------------------
void CMoteurAgenda::initBase   (const char* driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                                const char* DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                                const char* user,          // = "root"
                                const char* password,      // = ""
	                        const char* hostname,
			        const char* confFile,
                                const char* baseLabel,
			        QString*    errMess)
{ int ret;
  m_DriverName  = driver;
  m_BaseName    = DataBaseName;
  m_UserName    = user;
  m_PassWord    = password;
  m_HostName    = hostname;
  m_DataBase    = 0;
  QString mess;

  //................ configurer la classe .............................................
  if (confFile==0)                 {ret = 0; qDebug(mess + "\r\n ConfFile not found: " );}
  else if (confFile[0]==0)         {ret = 0; qDebug(mess + "\r\n ConfFile empty: "   );}
  else                             {ret = SetConfBase(confFile, &mess);          }

  if (ret==0)
     {qDebug(mess);
      if (errMess) *errMess = mess;
      return;
     }

  m_DataBase    = BaseConnect(driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                              DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                              user,          // = "root"
                              password,      // = ""
                              hostname,      // = "localhost"
                              errMess,
                              baseLabel);
}

//-----------------------------------------------------  ~CMoteurAgenda -------------------------------------------
CMoteurAgenda::~CMoteurAgenda()
{if (m_DataBase)
    {if (m_DataBase->isOpen()) m_DataBase->close();
     QSqlDatabase::removeDatabase (m_BaseLabel);
    }
}

//-----------------------------------------------------  BaseConnect -------------------------------------------
QSqlDatabase*  CMoteurAgenda::BaseConnect(const char* driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                                          const char* DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                                          const char* user,          // = "root"
                                          const char* pasword,       // = ""
                                          const char* hostname,      // = "localhost"
                                          QString*    errMess,
                                          QString     baseLabel)
    {
        m_BaseLabel             = baseLabel;
        QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( driver , baseLabel);
        if (defaultDB<=0) return 0;
        defaultDB->setDatabaseName( DataBaseName );
        defaultDB->setUserName( user );
        defaultDB->setPassword( pasword );
        defaultDB->setHostName( hostname);
        if ( ! defaultDB->open() )
	   {QString qstr = "";
            qstr += TR("Failed to open database: ") + QString(driver) + "  " + QString(DataBaseName) + "\r\n" +
	             defaultDB->lastError().driverText() + "\r\n" + defaultDB->lastError().databaseText();
            qWarning(qstr);
	    if (errMess) *errMess = qstr;
            return 0;
           }
        return defaultDB;
    }

//-----------------------------------------------------  SetConfBase -------------------------------------------
int CMoteurAgenda::SetConfBase(const char* confFile, QString *errMess)
{
  QString  err = "";
  char    *deb = (char*) confFile;
  char     *pt = (char*) confFile;
  int     line = 0;

  pt = SetConfBase_SetProperties(deb, m_AGENDA_TBL_NAME,   "m_AGENDA_TBL_NAME",  &line , err); if (err.length())     goto SetConfBase_Error;  // non de la table DU FICHIER GENERAL D'INDEX DES DOSSIERS
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_DATETIME,   "m_AGENDA_DATETIME",  &line , err); if (err.length())     goto SetConfBase_Error;  // date et heure du RDV
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_DUREE,      "m_AGENDA_DUREE",     &line , err); if (err.length())     goto SetConfBase_Error;  // duree (en minutes)  RDV
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_GUID,       "m_AGENDA_GUID",      &line , err); if (err.length())     goto SetConfBase_Error;  // un champ GUID unique qualifiant le numero de dossier du patient ayant ce RDV (si déjà connu)
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_NOM,        "m_AGENDA_NOM",       &line , err); if (err.length())     goto SetConfBase_Error;  // un champ NOM   qualifiant le nom du dossier
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_PRENOM,     "m_AGENDA_PRENOM",    &line , err); if (err.length())     goto SetConfBase_Error;  // un champ PRENOM   qualifiant le prenom du dossier
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_TEL,        "m_AGENDA_TEL",       &line , err); if (err.length())     goto SetConfBase_Error;  // téléphone (pour annuler)
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_PRIS_PAR,   "m_AGENDA_PRIS_PAR",  &line , err); if (err.length())     goto SetConfBase_Error;  // Utilisateur du programme
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_PRIS_AVEC,  "m_AGENDA_PRIS_AVEC", &line , err); if (err.length())     goto SetConfBase_Error;  // Médecin avec lequel le RDV a été pris
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_TYPE,       "m_AGENDA_TYPE",      &line , err); if (err.length())     goto SetConfBase_Error;  // Type de RDV
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_NOTE,       "m_AGENDA_NOTE",      &line , err); if (err.length())     goto SetConfBase_Error;  // Note
  pt = SetConfBase_SetProperties(pt,  m_AGENDA_PRIM_KEY,   "m_AGENDA_PRIM_KEY",  &line , err); if (err.length())     goto SetConfBase_Error;  // une clef primaire

  pt = SetConfBase_SetProperties(deb, m_COLOR_PROFIL_TBL_NAME,    "m_COLOR_PROFIL_TBL_NAME",  &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_COLOR_PROFIL_NAME,        "m_COLOR_PROFIL_NAME",      &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_COLOR_PROFIL_COLOR,       "m_COLOR_PROFIL_COLOR",     &line , err); if (err.length())     goto SetConfBase_Error;

  pt = SetConfBase_SetProperties(pt,  m_MASK_TBL_NAME,     "m_MASK_TBL_NAME",     &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_MASK_PRIM_KEY,     "m_MASK_PRIM_KEY",     &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_MASK_MOTIF,        "m_MASK_MOTIF",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_MASK_TYPE,         "m_MASK_TYPE",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_MASK_HEURE,        "m_MASK_HEURE",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_MASK_DUREE,        "m_MASK_DUREE",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_MASK_USER,         "m_MASK_USER",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_MASK_DAYOFWEEK,    "m_MASK_DAYOFWEEK",    &line , err); if (err.length())     goto SetConfBase_Error;

  return 1;

SetConfBase_Error:
  if (errMess) *errMess = err;
  qDebug(err);
  return 0;

}

//--------------------------------------------- SetConfBase_SetProperties ------------------------------------------------
char  *CMoteurAgenda::SetConfBase_SetProperties(char *pt, QString &propertie, const char *token, int *line , QString &err)
{int nLine = *line;
 err  = "";
 long len_token = strlen (token);
 while(*pt)
    {SKIP_BLANK_CAR(pt);
     if (strncmp(pt, token, len_token)==0)
        {//return pt+len_token;
	 pt         += len_token;
	 err         = "";
         propertie   = "";
         //............. chercher premier delimiteur ...............................
          while(*pt && *pt!='\r' && *pt !='\n' && *pt !='\'' ) pt++;
          if (*pt=='\'')         // si delimiteur pas trouve erreur
             {pt++;               // passer le delimiteur
              char *end = pt;
              //............. chercher deuxiéme delimiteur ...............................
              while(*end && *end!='\r' && *end !='\n' && *end !='\'')end++;
              if (*end=='\'')
                 {propertie.setLatin1(pt, end-pt);
		  if (line) *line = nLine;
	          return end +1;
                 }
              else
                {err  = TR("Syntax Error: SetConfBaseGetValue()\r\n End delimiter \"'\"  not find at line N°: ");
                 err += QString::number(nLine);
		 if (line) *line = nLine;
	         return 0;
                }
             }
           else
             {err  = TR("Syntax Error: SetConfBaseGetValue()\r\n Start delimiter \"'\"  not find at line N°: ");
              err += QString::number(nLine);
	      if (line) *line = nLine;
              return 0;
             }
        } //endif (strncmp(pt, token, len_token)==0)

     NEXT_LINE(pt);
     ++nLine;

    }
 err  = "Syntax Error: SetConfBase()\r\n";
 err += token;
 err += TR(" non trouvé à la ligne N°: ");
 err += QString::number(nLine);
 if (line) *line = nLine;
 return pt;
}

//--------------------------------------------- GotoDebug ------------------------------------------------
void CMoteurAgenda::GotoDebug()
{
}

//-------------------------------------- SetDaysHeight ----------------------------------------------------------------------------
void  CMoteurAgenda::SetDaysHeight(int val  /* = 15*/)
{m_DaysHeight = val;
}
//-------------------------------------- SetMinDaysHeight ----------------------------------------------------------------------------
void  CMoteurAgenda::SetMinDaysHeight(int val  /* = 15*/)
{m_MinDaysHeight = val;
}
//-------------------------------------- SetSpaceBetwenDays ----------------------------------------------------------------------------
void  CMoteurAgenda::SetSpaceBetwenDays(int val /* = 1*/)
{m_SpaceBetwenDays = val;
}
//-------------------------------------- GetDaysHeight ----------------------------------------------------------------------------
int  CMoteurAgenda::GetDaysHeight()
{return m_DaysHeight;
}
//-------------------------------------- GetMinDaysHeight ----------------------------------------------------------------------------
int  CMoteurAgenda::GetMinDaysHeight()
{return m_MinDaysHeight;
}
//-------------------------------------- GetSpaceBetwenDays ----------------------------------------------------------------------------
int  CMoteurAgenda::GetSpaceBetwenDays()
{return m_SpaceBetwenDays;
}
//-------------------------------------- MASK_Append ----------------------------------------------------------------------------
int CMoteurAgenda::MASK_Append(const RendezVous &rendezVous, QString *errMess /*=0*/)
{

  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::MASK_Append(): m_DataBase = 0 (create error)";         return FALSE; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::MASK_Append(): database can't be opened";              return FALSE; }
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_MASK_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ()) {m_DataBase->close(); return FALSE;}
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                         // recuperer le buffer d'insertion
  buffer->setValue( m_MASK_HEURE,         rendezVous.m_date.time() );
  buffer->setValue( m_MASK_DUREE,         (int)rendezVous.m_Duree );
  buffer->setValue( m_MASK_USER,          rendezVous.m_PrisAvec );
  buffer->setValue( m_MASK_TYPE,          rendezVous.m_Type );
  buffer->setValue( m_MASK_MOTIF,         rendezVous.m_Note );
  buffer->setValue( m_MASK_DAYOFWEEK,     rendezVous.m_date.date().dayOfWeek () );

  ok = cur.insert();                                          // ecrire le buffer avec les données
  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}

//--------------------------------------------- MASK_GetDay_RDV_List ------------------------------------------------
int CMoteurAgenda::MASK_GetDay_RDV_List(const QDate &date, const QString &user, RDV_LIST &rdvList, QString *errMess /*=0*/)
{ rdvList.clear();
  //................. ouvrir la base  ......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::MASK_GetDay_RDV_List(): m_DataBase = 0 (create error)";         return 0; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::MASK_GetDay_RDV_List(): database can't be opened";              return 0; }
  //................. Preparer la requete ..................................................
  QString requete("");
  requete  += "SELECT " + m_MASK_HEURE        +  ","         // 0
	                + m_MASK_DUREE        +  ","         // 1
	                + m_MASK_USER         +  ","         // 2
	                + m_MASK_TYPE         +  ","         // 3
	                + m_MASK_MOTIF        +  ","         // 4
	                + m_MASK_DAYOFWEEK    +  ","         // 5
	                + m_MASK_PRIM_KEY     +  " FROM  "   // 10
	                + m_MASK_TBL_NAME     +  " WHERE "
			+ m_MASK_DAYOFWEEK    +  " = '" + QString::number(date.dayOfWeek()) +  "' AND "
			+ m_MASK_USER         +  " = '" + user                              + "' ORDER BY " + m_MASK_HEURE;
  int nb = 0;
  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     { while (query.next())
	     {
	      rdvList.append(new RendezVous(QDateTime(date, query.value( 0 ).toTime()),   // date  QString       CGestIni::Utf8_Query(QSqlQuery &cur, int field);
                                            query.value( 1 ).toInt(),                     // duree
                                            "",                                           // nom
                                            "",                                           // prenom,
                                            "",                                           // tel,
                                            CGestIni::Utf8_Query(query, 4 ),                        // note,
                                            "",                                           // guid,
                                            "",                                           // prisPar,
                                            CGestIni::Utf8_Query(query, 2 ),                        // prisAvec,
                                            CGestIni::Utf8_Query(query, 3 ),                        // type,
                                            ""                                            // primKey
                                           )
                            );
	      ++ nb;
	     } //end while (pSqlQuery->next())
     } //endif (query.isActive())
  m_DataBase->close();
  return nb;
}

//-------------------------------------- MASK_DayDelete ----------------------------------------------------------------------------
int CMoteurAgenda::MASK_DayDelete( int dayOfWeek, const QString &user, QString *errMess /*=0*/)
{ //................. ouvrir la base  ......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::MASK_DayDelete(): m_DataBase = 0 (create error)";         return FALSE; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::MASK_DayDelete(): database can't be opened";              return FALSE; }
  //................. Preparer la requete ..................................................
  QString requete("DELETE FROM ");
          requete += m_MASK_TBL_NAME  + " WHERE "
                  +  m_MASK_USER      + "= '" + user                        + "' AND "
	          +  m_MASK_DAYOFWEEK + "= '" + QString::number(dayOfWeek)  + "'"  ;
  QSqlQuery query(QString::null , m_DataBase );
  query.exec(requete);
  m_DataBase->close();
  return TRUE;
}

//-------------------------------------- COL_Create ----------------------------------------------------------------------------
int CMoteurAgenda::COL_Create(const QString name, const QString color, QString *errMess /*=0*/)
{
  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::COL_Create(): m_DataBase = 0 (create error)";         return FALSE; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::COL_Create(): database can't be opened";              return FALSE; }
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_COLOR_PROFIL_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ()) {m_DataBase->close(); return FALSE;}
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                         // recuperer le buffer d'insertion
  buffer->setValue( m_COLOR_PROFIL_NAME,    name );
  buffer->setValue( m_COLOR_PROFIL_COLOR,   color );
  ok = cur.insert();                                          // ecrire le buffer avec les données
  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}

//--------------------------------------------- COL_Get_List ------------------------------------------------
int CMoteurAgenda::COL_Get_List(MAP_COLOR &colorProfils, QString *errMess /*=0*/)
{ colorProfils.clear();
  //................. ouvrir la base  ......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::COL_Get_List(): m_DataBase = 0 (create error)";         return 0; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::COL_Get_List(): database can't be opened";              return 0; }
  //................. Preparer la requete ..................................................
  QString requete="";
  requete  += "SELECT " + m_COLOR_PROFIL_NAME       +  ","         // 0
	                + m_COLOR_PROFIL_COLOR      +  " FROM  "   // 10
	                + m_COLOR_PROFIL_TBL_NAME ;
  int nb = 0;
  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     { while (query.next())
	     {colorProfils[query.value( 0 ).toString()] = query.value( 1 ).toString();
	      ++ nb;
	     } //end while (pSqlQuery->next())
     } //endif (query.isActive())
  m_DataBase->close();
  return nb;
}

//-------------------------------------- COL_Delete ----------------------------------------------------------------------------
int CMoteurAgenda::COL_Delete( const QString name, QString *errMess /*=0*/)
{ //................. ouvrir la base  ......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::RDV_Delete(): m_DataBase = 0 (create error)";         return FALSE; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::RDV_Delete(): database can't be opened";              return FALSE; }
  //................. Preparer la requete ..................................................
  QString requete("DELETE FROM ");
          requete += m_COLOR_PROFIL_TBL_NAME + " WHERE "
                  +  m_COLOR_PROFIL_NAME     + "= '" + name  + "'"  ;
  QSqlQuery query(QString::null , m_DataBase );
  query.exec(requete);
  m_DataBase->close();
  return TRUE;
}

//-----------------------------------------------------  RDV_IsThisRendezVousExist -------------------------------------------
QString CMoteurAgenda::RDV_IsThisRendezVousExist(const RendezVous &rendezVous, QString *errMess /*=0*/)
{
  QString ret("");
  //................. ouvrir la base  ......................................................
  if (m_DataBase==0)                                               {if (errMess) *errMess = ("CAnalyse::RDV_IsThisRendezVousExist(): m_DataBase = 0 (erreur lors creation) "); return ret; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)    {if (errMess) *errMess = ("CAnalyse::RDV_IsThisRendezVousExist(): Echec de l'ouverture de la base");        return ret; }
  //................. filtrer selon donnée d'entrée ..................................................
  QString reqDateDebStr = rendezVous.m_date.date().toString("yyyyMMdd") + rendezVous.m_date.time().toString("hhmm") + "00";
  QString requete("");
  requete  += "SELECT " + m_AGENDA_PRIM_KEY   +  " FROM  "
	                + m_AGENDA_TBL_NAME   +  " WHERE "
			+ m_AGENDA_DATETIME   +  " = '" + reqDateDebStr         + "' AND "
	                + m_AGENDA_NOM        +  " = '" + rendezVous.m_Nom      + "' AND "
	                + m_AGENDA_PRENOM     +  " = '" + rendezVous.m_Prenom   + "' AND "
	                + m_AGENDA_PRIS_AVEC  +  " = '" + rendezVous.m_PrisAvec + "' AND "
	                + m_AGENDA_TYPE       +  " = '" + rendezVous.m_Type     + "' ";

  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  if (query.isActive() && query.next())
     {ret   = query.value(0).toString();
     }

  m_DataBase->close();
  return ret;
}

//-------------------------------------- RDV_Create ----------------------------------------------------------------------------
int CMoteurAgenda::RDV_Create(const RendezVous &rendezVous, QString *errMess /*=0*/)
{
  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::RDV_Create(): m_DataBase = 0 (create error)";         return FALSE; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::RDV_Create(): database can't be opened";              return FALSE; }
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_AGENDA_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ()) {m_DataBase->close(); return FALSE;}
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                         // recuperer le buffer d'insertion
  buffer->setValue( m_AGENDA_DATETIME,    rendezVous.m_date );
  buffer->setValue( m_AGENDA_DUREE,       (int)rendezVous.m_Duree );
  buffer->setValue( m_AGENDA_GUID,        rendezVous.m_GUID );
  buffer->setValue( m_AGENDA_NOM,         rendezVous.m_Nom );
  buffer->setValue( m_AGENDA_PRENOM,      rendezVous.m_Prenom );
  buffer->setValue( m_AGENDA_TEL,         rendezVous.m_Tel );
  buffer->setValue( m_AGENDA_PRIS_PAR,    rendezVous.m_PrisPar );
  buffer->setValue( m_AGENDA_PRIS_AVEC,   rendezVous.m_PrisAvec );
  buffer->setValue( m_AGENDA_TYPE,        rendezVous.m_Type );
  buffer->setValue( m_AGENDA_NOTE,        rendezVous.m_Note );
  ok = cur.insert();                                          // ecrire le buffer avec les données
  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}

//-------------------------------------- RDV_Update ----------------------------------------------------------------------------
int CMoteurAgenda::RDV_Update(const RendezVous &rendezVous, QString *errMess /*=0*/)
{
  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::RDV_Update(): m_DataBase = 0 (create error)";         return FALSE; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::RDV_Update(): database can't be opened";              return FALSE; }
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_AGENDA_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canUpdate ()) {m_DataBase->close(); return FALSE;}
  //............... placer ce curseur sur le bon enregistrement ..........................
  cur.select(m_AGENDA_PRIM_KEY  + "='" + rendezVous.m_PrimKey  + "'" );
  //............... si OK on recupere le buffer et on le charge avec les données .........
  if ( cur.next() )
     {QSqlRecord *buffer = cur.primeUpdate();                         // recuperer le buffer d'insertion
      buffer->setValue( m_AGENDA_DATETIME,    rendezVous.m_date );
      buffer->setValue( m_AGENDA_DUREE,       (int)rendezVous.m_Duree );
      buffer->setValue( m_AGENDA_GUID,        rendezVous.m_GUID );
      buffer->setValue( m_AGENDA_NOM,         rendezVous.m_Nom );
      buffer->setValue( m_AGENDA_PRENOM,      rendezVous.m_Prenom );
      buffer->setValue( m_AGENDA_TEL,         rendezVous.m_Tel );
      buffer->setValue( m_AGENDA_PRIS_PAR,    rendezVous.m_PrisPar );
      buffer->setValue( m_AGENDA_PRIS_AVEC,   rendezVous.m_PrisAvec );
      buffer->setValue( m_AGENDA_TYPE,        rendezVous.m_Type );
      buffer->setValue( m_AGENDA_NOTE,        rendezVous.m_Note );
      ok = cur.update();                                          // ecrire le buffer avec les données
     }
  if (ok==0) OutSQL_error(cur, "PatientNoteUpdate()");
  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}

//-------------------------------------- RDV_Delete ----------------------------------------------------------------------------
int CMoteurAgenda::RDV_Delete( const QString &primKey, QString *errMess /*=0*/)
{ //................. ouvrir la base  ......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::RDV_Delete(): m_DataBase = 0 (create error)";         return FALSE; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::RDV_Delete(): database can't be opened";              return FALSE; }
  //................. Preparer la requete ..................................................
  QString requete("DELETE FROM ");
          requete += m_AGENDA_TBL_NAME       + " WHERE "
                  +  m_AGENDA_PRIM_KEY       + "= '"       + primKey  + "' ";
  QSqlQuery query(QString::null , m_DataBase );
  query.exec(requete);
  m_DataBase->close();
  return TRUE;
}

//--------------------------------------------- RDV_Get_List ------------------------------------------------
int CMoteurAgenda::RDV_Get_List(QDate date, const QString &user, RDV_LIST &rdvList, int mode /*= CMoteurAgenda::AllDates*/, QString *errMess /*=0*/)
{ rdvList.clear();
  //................. ouvrir la base  ......................................................
  if (m_DataBase==0)                                            {if (errMess) *errMess = "CMoteurAgenda::RDV_Get_List(): m_DataBase = 0 (create error)";         return 0; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurAgenda::RDV_Get_List(): database can't be opened";              return 0; }
  //................. Preparer la requete ..................................................
  QString reqDateDebStr = date.toString("yyyyMMdd") + "000000";
  QString reqDateEndStr = date.toString("yyyyMMdd") + "235959";
  QString requete("");
  requete  += "SELECT " + m_AGENDA_DATETIME   +  ","         // 0
	                + m_AGENDA_DUREE      +  ","         // 1
	                + m_AGENDA_GUID       +  ","         // 2
	                + m_AGENDA_NOM        +  ","         // 3
	                + m_AGENDA_PRENOM     +  ","         // 4
	                + m_AGENDA_TEL        +  ","         // 5
	                + m_AGENDA_PRIS_PAR   +  ","         // 6
	                + m_AGENDA_PRIS_AVEC  +  ","         // 7
	                + m_AGENDA_TYPE       +  ","         // 8
	                + m_AGENDA_NOTE       +  ","         // 9
	                + m_AGENDA_PRIM_KEY   +  " FROM  "   // 10
	                + m_AGENDA_TBL_NAME   +  " WHERE "
			+ m_AGENDA_DATETIME   +  " >= '" + reqDateDebStr + "' AND " + m_AGENDA_DATETIME + "<= '" + reqDateEndStr + "' AND "
			+ m_AGENDA_PRIS_AVEC  +  "  = '" + user + "' ORDER BY " + m_AGENDA_DATETIME;
  int nb = 0;
  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     { while (query.next())
	     {bool ok = TRUE;
	      if (mode == CMoteurAgenda::OnlyDateWhithName && query.value(3).toString().length()==0) ok = FALSE;
	      if (ok){rdvList.append(new RendezVous(query.value( 0 ).toDateTime(),   // date
                                                    query.value( 1 ).toInt(),        // duree
                                                    CGestIni::Utf8_Query(query, 3 ),           // nom
                                                    CGestIni::Utf8_Query(query, 4 ),           // prenom,
                                                    query.value( 5 ).toString(),     // tel,
                                                    CGestIni::Utf8_Query(query, 9 ),           // note,
                                                    query.value( 2 ).toString(),     // guid,
                                                    CGestIni::Utf8_Query(query, 6 ),           // prisPar,
                                                    CGestIni::Utf8_Query(query,7 ),            // prisAvec,
                                                    CGestIni::Utf8_Query(query, 8),            // type,
                                                    query.value( 10).toString()      // primKey
                                                   )
                                    );
		      ++ nb;
	             } //end if (ok)
	     } //end while (pSqlQuery->next())
     } //endif (query.isActive())
  m_DataBase->close();
  return nb;
}

//-------------------------------------------------- dayOfWeek -----------------------------------------------
QString CMoteurAgenda::dayOfWeek(int dayOfWeek)
{
 switch(dayOfWeek)
        { case 1:  return  TR( "Lundi");
          case 2:  return  TR( "Mardi");
          case 3:  return  TR( "Mercredi");
          case 4:  return  TR( "Jeudi");
          case 5:  return  TR( "Vendredi");
          case 6:  return  TR( "Samedi");
          case 7:  return  TR( "Dimanche");
        }
 return QString::null;
}

//-------------------------------------------------- OutSQL_error -----------------------------------------------
void CMoteurAgenda::OutSQL_error(QSqlQuery &cur, const char *messFunc /*=0*/, const char *requete /*=0*/)
{    QSqlError error = cur.lastError();
     QString   qserr("");

     if (error.type() != QSqlError::None)
        {switch (error.type())
           { case    QSqlError::None:           qserr = TR(" - no error occurred: ")          ; break;
             case    QSqlError::Connection:     qserr = TR(" - connection error: ")           ; break;
             case    QSqlError::Statement:      qserr = TR(" - SQL statement syntax error: ") ; break;
             case    QSqlError::Transaction:    qserr = TR(" - transaction failed error: ")   ; break;
	     case    QSqlError::Unknown:        qserr = TR(" - unknown error: ")              ; break;
	     default:                           qserr = TR(" - unknown error: ")              ; break;
           }
	 if (messFunc) qDebug(messFunc);
         qDebug(qserr + error.databaseText ());
	 if (requete) qDebug(requete);
        }
}


