/****************************************************************************
** ui.h extension file, included from the uic-generated form implementation.
**
** If you wish to add, delete or rename functions or slots use
** Qt Designer which will update this file, preserving your code. Create an
** init() function in place of a constructor, and a destroy() function in
** place of a destructor.
*****************************************************************************/
#include <qsqlform.h>
#include <qsqldatabase.h>
#include <qstring.h>
#include <qrect.h>
#include <qmessagebox.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qlistbox.h>
#define LIST_COMPLETE  1

//--------------------------------- Init -------------------------------------------------------------
void Praticien_Dlg::init()
{QString qstr;
 m_Droits = "";
 pushButtonOK->hide();
 text_Label_Status->setText(tr( "Bienvenue sur Annuaire - Sevin Roland" ));
 int nb_arg = G_pCApp->argc();                 // 0 = path programme   1 = fichier patient
 if (nb_arg >= 1)
    {QString path ( G_pCApp->argv()[ 1 ] );
// Annulé par Gérard     setCaption(path);
     setCaption(tr("Annuaire - Data Medical Design"));
     if (nb_arg > 1) pushButtonOK->show();
    }
 comboBox_Specialite->setDuplicatesEnabled ( FALSE );
 comboBox_Specialite->setInsertionPolicy ( QComboBox::AtBottom );
 comboBoxSpec->setDuplicatesEnabled ( FALSE );
 comboBoxSpec->setInsertionPolicy ( QComboBox::AtBottom );
 //comboBox_Specialite->lineEdit()->setFrameRect (QRect(0,0,10,100) );
 //............... connexion à la base de données ............................................................
 m_DataBase  = G_pCApp->m_DataBase;     // créer et noter la connexion
                                        // cassos si echec de la connexion
  //............... scann de tous les enregistrements et creation liste d'index ................................
 InitAllList(tr("Toutes Spécialités"));
 listBoxChoixNom_currentChanged(  listBoxChoixNom->firstChild()  );
 lineEditAutoLocator->setFocus();
 lineEditAutoLocator->setMixMode(1);
 lineEditAutoLocator->setText("");
 connect( lineEditAutoLocator, SIGNAL( Sig_CarEvent(QEvent * )),
          this,                SLOT(   EditAutoLocatorChanged(QEvent * ))
        );
connect( lineEditAutoLocator,   SIGNAL( Sig_KeyDown ()),
             this,               SLOT(   OnSign_NomKeyDown())
           );
 connect( lineEditAutoLocator,   SIGNAL( Sig_KeyUp ()),
               this,             SLOT(    OnSign_NomKeyUp())
           );
 connect( lineEditAutoLocator,   SIGNAL(   returnPressed ()),
               this,             SLOT(      lineEditAutoLocator_returnPressed())
        );

// connect( lineEditAutoLocator, SIGNAL( textChanged (const QString&)),
//          this,                SLOT(   EditAutoLocatorChanged(const QString&))
//        );
 connect( lineEdit_Ville, SIGNAL( Sig_FocusOut ()),
          this,     SLOT(   OnOutFocusVille())
        );
 connect( lineEdit_CodePostal, SIGNAL( Sig_FocusOut()),
                   this,     SLOT(   OnOutFocusCodePostal())
                );
 connect( lineEdit_CodePostal, SIGNAL( Sig_CarEvent(QEvent* )),
                   this,     SLOT(   OnCharEventCodePostal(QEvent* ))
                );

 connect( comboBoxTelTyp_1->lineEdit(), SIGNAL( lostFocus ()), this,     SLOT(   On_ComboBoxLostFocus_TelTyp_1()) );
 connect( comboBoxTelTyp_2->lineEdit(), SIGNAL( lostFocus ()), this,     SLOT(   On_ComboBoxLostFocus_TelTyp_2()) );
 connect( comboBoxTelTyp_3->lineEdit(), SIGNAL( lostFocus ()), this,     SLOT(   On_ComboBoxLostFocus_TelTyp_3()) );
 InitAllComboTelType();
 m_CurrentPopupItem = "";
 m_RetPopupItem     = "";
 m_pQPopupMenu      = 0;
 setIcon( G_pCApp->m_PathAppli + "Images/Personnes.png" );
 if (nb_arg <= 1) setCaption(tr("Annuaire - Data Medical Design"));
 else             pushButtonOK->show();
 //....................... se positionner sur item donne en entree .........................
 if (G_pCApp->m_Start_ID.length())
    {QListViewItemIterator it( listBoxChoixNom );
     while ( it.current() )
           {
            CMyQListViewItem *item = (CMyQListViewItem*) it.current();
            if (item->m_ExData == G_pCApp->m_Start_ID)
                {listBoxChoixNom->setCurrentItem ((QListViewItem*)item );
                 listBoxChoixNom->setCurrentItem ((QListViewItem*)item );
                 listBoxChoixNom->setSelected ( (QListViewItem*)item , true) ;
                 listBoxChoixNom->ensureItemVisible ((QListViewItem*) item );
                }
            ++it;
           }
    }
}

//--------------------------------- On_ComboBoxLostFocus_TelTyp_1 -----------------------------------------------------------------------
void  Praticien_Dlg::On_ComboBoxLostFocus_TelTyp_1()
{QString str =  comboBoxTelTyp_1->lineEdit()->text().stripWhiteSpace();
 AddThisItemIfNotExist(comboBoxTelTyp_1, str);
 AddThisItemIfNotExist(comboBoxTelTyp_2, str);
 AddThisItemIfNotExist(comboBoxTelTyp_3, str);
}

//--------------------------------- On_ComboBoxLostFocus_TelTyp_2 -----------------------------------------------------------------------
void  Praticien_Dlg::On_ComboBoxLostFocus_TelTyp_2()
{QString str =  comboBoxTelTyp_2->lineEdit()->text().stripWhiteSpace();
 AddThisItemIfNotExist(comboBoxTelTyp_1, str);
 AddThisItemIfNotExist(comboBoxTelTyp_2, str);
 AddThisItemIfNotExist(comboBoxTelTyp_3, str);
}

//--------------------------------- On_ComboBoxLostFocus_TelTyp_3 -----------------------------------------------------------------------
void  Praticien_Dlg::On_ComboBoxLostFocus_TelTyp_3()
{QString str =  comboBoxTelTyp_3->lineEdit()->text().stripWhiteSpace();
 AddThisItemIfNotExist(comboBoxTelTyp_1, str);
 AddThisItemIfNotExist(comboBoxTelTyp_2, str);
 AddThisItemIfNotExist(comboBoxTelTyp_3, str);
}

//--------------------------------- InitAllComboTelType -----------------------------------------------------------------------
void  Praticien_Dlg::InitAllComboTelType()
{    if (m_DataBase==0)                                              return ;
     if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return ;
     QStringList itemList;
     QString val_1, val_2, val_3;

       {
        //.................. fabriquer la requete ........................
        //                   de selection de l'enregistrement
        //                   correspondant à la cle
        QString requete ("SELECT ");
        requete    +=  G_pCApp->m_INTERVENANTS_TEL_TYPE_1      + ","
                     + G_pCApp->m_INTERVENANTS_TEL_TYPE_2      + ","
                     + G_pCApp->m_INTERVENANTS_TEL_TYPE_3      + " " ;

        requete += " FROM " + G_pCApp->m_INTERVENANTS_TBL_NAME;
        //char *pt = (char*) (const char*) requete;
        QSqlQuery query(requete, m_DataBase);
        if (query.isActive())
           {while (query.next())
                  { val_1 = Utf8_Query(query,0).stripWhiteSpace();
                    val_2 = Utf8_Query(query,1).stripWhiteSpace();
                    val_3 = Utf8_Query(query,2).stripWhiteSpace();

                    if (val_1.length() && itemList.findIndex ( val_1 )==-1) itemList.append(val_1);
                    if (val_2.length() && itemList.findIndex ( val_2 )==-1) itemList.append(val_2);
                    if (val_3.length() && itemList.findIndex ( val_3 )==-1) itemList.append(val_3);
                  }
           }
        else  OutSQL_error(query , "InitAllComboTelType()", requete );
       }
     m_DataBase->close();
     comboBoxTelTyp_1->insertStringList ( itemList );
     comboBoxTelTyp_2->insertStringList ( itemList );
     comboBoxTelTyp_3->insertStringList ( itemList );
}

//--------------------------------- AddThisItemIfNotExist -----------------------------------------------------------------------
void  Praticien_Dlg::AddThisItemIfNotExist(QComboBox *pQComboBox, const QString &str)
{ if (str.length()==0) return;
  QListBox         *pQListBox =  pQComboBox->listBox ();
  QListBoxItem *pQListBoxItem =  pQListBox->findItem ( str, Qt::ExactMatch );
  if (pQListBoxItem==0) pQComboBox->insertItem (str);
}

//--------------------------------- OnSign_NomKeyDown -----------------------------------------------------------------------
void  Praticien_Dlg::OnSign_NomKeyDown()
{QListViewItem *pQListViewItem =  listBoxChoixNom->currentItem ();
 if ( pQListViewItem == 0)                 return;
 if ( pQListViewItem->itemBelow () ==0 )   return;
 pQListViewItem =  pQListViewItem->itemBelow ();
 listBoxChoixNom->setCurrentItem (pQListViewItem );
 listBoxChoixNom->ensureItemVisible ( pQListViewItem );
}

//--------------------------------- OnSign_NomKeyUp -----------------------------------------------------------------------
void  Praticien_Dlg::OnSign_NomKeyUp()
{QListViewItem *pQListViewItem =  listBoxChoixNom->currentItem ();
 if ( pQListViewItem == 0 )                return;
 if ( pQListViewItem->itemAbove () ==0 )   return;
 pQListViewItem = pQListViewItem->itemAbove ();
 listBoxChoixNom->setCurrentItem (pQListViewItem );
 listBoxChoixNom->ensureItemVisible ( pQListViewItem );
}

//--------------------------------- lineEditAutoLocator_returnPressed -----------------------------------------------------------------------
void  Praticien_Dlg::lineEditAutoLocator_returnPressed()
{pushButtonOK_clicked();
}

//--------------------------------- OnOutFocusVille -----------------------------------------------------------------------
void  Praticien_Dlg::OnOutFocusVille()
{//if (m_pCMoteurBase==0) return;
 QString codePostal("");
 QString ville = lineEdit_Ville->text().stripWhiteSpace();
 //.......... si pas de ville saisie on tente avec le code postal .........................
 if (ville.length()==0)
    {OnOutFocusCodePostal();
     return;
    }
 //............... chercher liste de codepostaux pouvant correspondre à cette ville .............
 QStringList codePostalList;
 G_pCApp->GetCodePostalFromVille( ville.replace("SAINT ","ST "),  codePostalList);
 if (codePostalList.findIndex ( lineEdit_CodePostal->text()+" "+lineEdit_Ville->text() ) != -1 ) return;

 int nb = codePostalList.count();
 if (nb==1)
    {codePostal = codePostalList[0];
    }
 else if (nb>1 && nb<35 )
    {
     codePostal = DoPopupList(codePostalList, lineEdit_Ville->x(), lineEdit_Ville->y());
    }
 //............ separer la ville du code postal ...................................................
 int pos = codePostal.find(' ');
 if (pos != -1)
    {ville      = codePostal.mid(pos+1);
     codePostal = codePostal.left(pos);
    }
 if (//lineEdit_CodePostal->text().length()<5           ||                               // si code postal incomplet
     (codePostal.length()!=0 /*&& lineEdit_CodePostal->text() != codePostal */)            // ou non conforme avec celui de la ville
    )
    {lineEdit_CodePostal->setText(codePostal );                                        // placer celui de la ville
     lineEdit_Ville->setText(ville);
     return;
    }

 //.............. si pas de code postal trouvé pour cette ville tenter de placer la ville du code postal .............
 if (codePostal.length()==0 )
    {ville = G_pCApp->GetVilleFromCodePostal(lineEdit_CodePostal->text());
     if (ville.length()!=0) lineEdit_Ville->setText(ville);
    }
}

//--------------------------------- OnOutFocusCodePostal -------------------------------------------------------------
void  Praticien_Dlg::OnOutFocusCodePostal()
{//if (m_pCMoteurBase==0) return;
 QStringList villeList;
 if (lineEdit_CodePostal->text().length()==5)
    {G_pCApp->GetVilleFromCodePostal(lineEdit_CodePostal->text(), villeList);
     int nb = villeList.count();
     if (nb==1)
        {lineEdit_Ville->setText(villeList[0]);
        }
     else if (nb>1 && nb<35 )
        {if (villeList.findIndex ( lineEdit_Ville->text()) == -1 )  // si la ville ne correspond pas au code postal
            {QString ville = DoPopupList(villeList, lineEdit_CodePostal->x(), lineEdit_CodePostal->y());
             if (ville.length()>0) lineEdit_Ville->setText(ville);
            }
        }
    }
 else
    {lineEdit_Ville->clear();
    }
}

//--------------------------------- DoPopupList ----------------------------------------------------------------------
QString Praticien_Dlg::DoPopupList(QStringList &list, int x ,int y)
{m_CurrentPopupItem = "";
 m_RetPopupItem     = "";
 if (m_pQPopupMenu) return m_RetPopupItem;
 m_pQPopupMenu      = new QPopupMenu(0, "MyPopupMenu" );
 if (m_pQPopupMenu==0)       return m_RetPopupItem;
 //............................... chercher une zone de liste deroulante (bleue) .....................
 for ( QStringList::Iterator it =list.begin(); it != list.end(); ++it )
    {m_pQPopupMenu->insertItem( *(it),    this, SLOT( GetPopupItem()),  CTRL+Key_L );
    }
 //................. connecter le menu .................................................................
 connect( m_pQPopupMenu, SIGNAL( activated( int)),
          this,          SLOT(OnMenuActivated( int))
        );

 m_pQPopupMenu->exec(mapToGlobal (QPoint ( x, y)));
 delete  m_pQPopupMenu;
 m_pQPopupMenu = 0;
 return  m_RetPopupItem;
}

//--------------------------------- OnMenuActivated  -------------------------------------------------------------
void Praticien_Dlg::OnMenuActivated (int id)
{if (id != -1 && m_pQPopupMenu)
    {m_CurrentPopupItem = m_pQPopupMenu->text(id);
    }
}

//--------------------------------- GetPopupItem  -------------------------------------------------------------
void Praticien_Dlg::GetPopupItem ()
{m_RetPopupItem  = m_CurrentPopupItem;
}

//--------------------------------- OnCharEventCodePostal -------------------------------------------------------------
void  Praticien_Dlg::OnCharEventCodePostal(QEvent* )
{OnOutFocusCodePostal();
}


//--------------------------------- ItemToForm -------------------------------------------------------
void Praticien_Dlg::ItemToForm( CMyQListViewItem* pCMyQListViewItem )
{    if (m_DataBase==0)                                              return ;
     if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return ;

     if (pCMyQListViewItem != 0)
       {
        //.................. fabriquer la requete ........................
        //                   de selection de l'enregistrement
        //                   correspondant à la cle
        QString requete ("SELECT ");
        requete    +=  G_pCApp->m_INTERVENANTS_NOM             + ","     // 0
                     + G_pCApp->m_INTERVENANTS_PRENOM          + ","     // 1
                     + G_pCApp->m_INTERVENANTS_ADRESSE         + ","     // 2
                     + G_pCApp->m_INTERVENANTS_CODE_POST       + ","     // 3
                     + G_pCApp->m_INTERVENANTS_VILLE           + ","     // 4
                     + G_pCApp->m_INTERVENANTS_TEL_1           + ","     // 5
                     + G_pCApp->m_INTERVENANTS_TEL_2           + ","     // 6
                     + G_pCApp->m_INTERVENANTS_TEL_3           + ","     // 7
                     + G_pCApp->m_INTERVENANTS_EMAIL           + ","     // 8
                     + G_pCApp->m_INTERVENANTS_NOTE            + ","     // 9
                     + G_pCApp->m_INTERVENANTS_QUALITE         + ","     // 10
                     + G_pCApp->m_INTERVENANTS_TITRE           + ","     // 11
                     + G_pCApp->m_INTERVENANTS_TEL_ABR_1       + ","     // 12
                     + G_pCApp->m_INTERVENANTS_TEL_ABR_2       + ","     // 13
                     + G_pCApp->m_INTERVENANTS_TEL_ABR_3       + ","     // 14
                     + G_pCApp->m_INTERVENANTS_DROITS          + ","     // 15
                     + G_pCApp->m_INTERVENANTS_TEL_TYPE_1      + ","     // 16
                     + G_pCApp->m_INTERVENANTS_TEL_TYPE_2      + ","     // 17
                     + G_pCApp->m_INTERVENANTS_TEL_TYPE_3      + ","     // 18
                     + G_pCApp->m_INTERVENANTS_SEXE                      // 19
                  ;

        requete += " FROM " + G_pCApp->m_INTERVENANTS_TBL_NAME + " WHERE " + G_pCApp->m_INTERVENANTS_PK + "='";
        requete +=  pCMyQListViewItem->m_ExData + "'";

        QSqlQuery query(requete, m_DataBase);
        if (query.isActive())
           {while (query.next())
                  {
                    lineEdit_Nom->setText(Utf8_Query(query,0));
                    lineEdit_Prenom->setText(Utf8_Query(query,1));
                    textEdit_Rue->setText(Utf8_Query(query,2));
                    lineEdit_CodePostal->setText(Utf8_Query(query,3));
                    lineEdit_Ville->setText(Utf8_Query(query,4));
                    lineEdit_Tel_1->setText(Utf8_Query(query,5));
                    lineEdit_Tel_2->setText(Utf8_Query(query,6));
                    lineEdit_Tel_3->setText(Utf8_Query(query,7));
                    lineEdit_Email->setText(Utf8_Query(query,8));
                    textEdit_Note->setText(Utf8_Query(query,9));
                             comboBox_Specialite->setEditText(Utf8_Query(query,10));
                    lineEdit_Titre->setText(Utf8_Query(query,11));
                    lineEdit_Code_1->setText(Utf8_Query(query,12));
                    lineEdit_Code_2->setText(Utf8_Query(query,13));
                    lineEdit_Code_3->setText(Utf8_Query(query,14));
                    m_Droits         = Utf8_Query(query,15);
                    comboBoxTelTyp_1->lineEdit()->setText(Utf8_Query(query,16));
                    comboBoxTelTyp_2->lineEdit()->setText(Utf8_Query(query,17));
                    comboBoxTelTyp_3->lineEdit()->setText(Utf8_Query(query,18));
                    QString sex = Utf8_Query(query,19);
                    if (sex=="M") comboBoxSexe->setCurrentItem (0);
                    else          comboBoxSexe->setCurrentItem (1);
                  }
           }
        else  OutSQL_error(query , "ItemToForm()", requete );
       }
     m_DataBase->close();
}

//--------------------------------- Utf8_Query ------------------------------------------------------------
QString Praticien_Dlg::Utf8_Query(QSqlQuery &cur, int field)
{QCString     cString  = cur.value(field).toCString ();
 char *ptr             =  cString.data();
 if (CGestIni::IsUtf8( ptr ))
    {return QString::fromUtf8 ( ptr );
    }
 else
    {return QString(ptr) ;
    }

}

//--------------------------------- OutSQL_error ------------------------------------------------------------
void Praticien_Dlg::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 =" - no error occurred: "          ; break;
             case    QSqlError::Connection:     qserr =" - connection error: "           ; break;
             case    QSqlError::Statement:      qserr =" - SQL statement syntax error: " ; break;
             case    QSqlError::Transaction:    qserr =" - transaction failed error: "   ; break;
             case    QSqlError::Unknown:        qserr =" - unknown error: "              ; break;
             default:                           qserr =" - unknown error: "              ; break;
           }
         if (messFunc) qDebug(messFunc);
         qDebug(qserr + error.databaseText ());
         if (requete) qDebug(requete);
        }
//     qDebug(qserr + error.databaseText ());
}
//--------------------------------- OnButtonNouvelleFiche ------------------------------------------------------------
void Praticien_Dlg::OnButtonNouvelleFiche()
{//.......... si Mode = Creation d'une fiche en cours ............................
 //           (listBoxChoixNom est alors cachée) et que ce
 //           bouton est appuyé --> annuler la creation en cours (tout remettre en visible)
 if (listBoxChoixNom->isHidden ())
    {listBoxChoixNom->setHidden (FALSE );
     lineEditAutoLocator->setHidden (FALSE );
     textLabel_Rechercher->setHidden (FALSE );
     textLabel_StateList->setHidden (FALSE );
     comboBoxSpec->setHidden (FALSE );
     pushButton_Effacer->setHidden (FALSE );
     pushButton_Modifier->setText(tr("&Enregistrer les modifications"));
     pushButton_Nouvelle->setText(tr("&Créer une nouvelle fiche"));
     text_Label_Status->setText(tr("Bienvenue sur Annuaire - Sevin Roland"));
     if (G_pCApp->argc() > 1) pushButtonOK->show();
    }
 //.......... si Mode = Consultation des fiches en cours ............................
 //           (listBoxChoixNom est alors visible) et que ce
 //           bouton est appuyé --> Se mettre en mode creation (cacher les outils de consultation)
 else
    {listBoxChoixNom->setHidden (TRUE );
     lineEditAutoLocator->setHidden (TRUE );
     textLabel_Rechercher->setHidden (TRUE );
     textLabel_StateList->setHidden (TRUE );
     comboBoxSpec->setHidden (TRUE );
     pushButton_Effacer->setHidden (TRUE );
     //........ "Enregistrer les modifications" ....................
     pushButton_Modifier->setText(tr("Créer et a&jouter cette fiche"));
     //........ "Créer une nouvelle Fiche" ....................
     pushButton_Nouvelle->setText(tr("Annu&ler la création de fiche"));
     text_Label_Status->setText(tr("Fiche en cours de création"));
     pushButtonOK->hide();
     ClearSaisie();
    }
}
//------------------------------------------- ClearSaisie ------------------------------------------------------------
void Praticien_Dlg::ClearSaisie()
{lineEdit_Nom->setText("");
 lineEdit_Prenom->setText("");
 lineEdit_Titre->setText("");
 lineEdit_NumOrd->setText("");
 lineEdit_CodePostal->setText("");
 lineEdit_Ville->setText("");
 lineEdit_Tel_1->setText("");
 lineEdit_Tel_2->setText("");
 lineEdit_Tel_3->setText("");
 lineEdit_Code_1->setText("");
 lineEdit_Code_2->setText("");
 lineEdit_Code_3->setText("");
 lineEditAutoLocator->setText("");
 textEdit_Rue->setText("");
 textEdit_Note->setText("");
 lineEdit_Email->setText("");
 //InitAllComboTelType();
 comboBoxTelTyp_1->lineEdit()->setText("");
 comboBoxTelTyp_2->lineEdit()->setText("");
 comboBoxTelTyp_3->lineEdit()->setText("");
}

//--------------------------------- OnBoutonMisAJourFiche ------------------------------------------------------------
void Praticien_Dlg::OnBoutonMisAJourFiche()
{//.......... si Mode = Creation d'une fiche en cours ............................
 //           (listBoxChoixNom est alors cachée) et que ce
 //           bouton est appuyé --> confirmer la creation en cours
 if (listBoxChoixNom->isHidden ())
    {
     CMyQListViewItem* pCMyQListViewItem = FormToDisk(0);                 // inserer la fiche dans la base de données
     //........... replacer les outils de conultation en visible ..........................
     listBoxChoixNom->setHidden (FALSE );
     lineEditAutoLocator->setHidden (FALSE );
     textLabel_Rechercher->setHidden (FALSE );
     textLabel_StateList->setHidden (FALSE );
     comboBoxSpec->setHidden (FALSE );
     pushButton_Effacer->setHidden (FALSE );
     pushButton_Modifier->setText(tr("&Enregistrer les modifications"));
     pushButton_Nouvelle->setText(tr("&Créer une nouvelle fiche"));
     if (G_pCApp->argc() > 1) pushButtonOK->show();
     if (pCMyQListViewItem==0)                                                     return;
     //........... reinitialiser les combo-box ..................
     //InitAllList("Toutes Spécialités");
     InitComboSpec();
     QString num;
     text_Label_Status->setText(num.sprintf(tr("Enregistrement N°: %s créé."), (const char*) pCMyQListViewItem->m_ExData));
     listBoxChoixNom->setCurrentItem(pCMyQListViewItem);
    }
 //.......... si Mode = Consultation des fiches en cours ............................
 //           (listBoxChoixNom est alors visible) et que ce
 //           bouton est appuyé --> mettre à jour la fiche en cours
 else
    {CMyQListViewItem* pCMyQListViewItem =  (CMyQListViewItem*) listBoxChoixNom->currentItem();
     if (pCMyQListViewItem != 0 && FormToDisk(pCMyQListViewItem) != 0)
        {ItemToForm(pCMyQListViewItem);
         //listBoxChoixNom_currentChanged( pCMyQListViewItem );
         QString num;
         text_Label_Status->setText(num.sprintf(tr("Fiche N°: %s mise à jour."), (const char*) pCMyQListViewItem->m_ExData));
        }
    }
}

//--------------------------------- OnBoutonEffacer ------------------------------------------------------------
void Praticien_Dlg::OnBoutonEffacer()
{CMyQListViewItem* pCMyQListViewItem = (CMyQListViewItem*)listBoxChoixNom->currentItem();
 if (pCMyQListViewItem != 0)
    {int ret = 0;
     /*
     if (m_Droits.find("med") != -1 &&   m_Droits.find("adm") != -1)        // med-adm
        { QMessageBox::warning (this,"Annuaire",
                                 tr("<u><b>ATTENTION ! </b></u> vous vous apprétez à effacer un utilisateur<br>"
                                 "de <b> MedinTux </b> L'effacement de cette fiche peut en perturber<br>"
                                 "le fonctionnement.<br> Soyez sûr de cette action."),
                                 tr("&Effacer"),tr("&Ne Rien Faire"),0,1);
        }
     else if (m_Droits.find("med")!= -1)
        {QMessageBox::warning (this,"Annuaire",
                                 tr("<u><b>ATTENTION  </b></u> les utilisateurs de <b> MedinTux </b><br>"
                                 " ne peuvent être effacés que si vous disposez des droits <br>"
                                 " <b> administrateur </b> ."),
                                 0,0,0,1);
        ret = 1;
        }
     */
     if (m_Droits.find("med")!= -1)
        {QMessageBox::warning (this,"Annuaire",
                                 tr("<u><b>ATTENTION  </b></u> les utilisateurs de <b> MedinTux </b><br>"
                                 " ne peuvent être effacés qu'à partir du gestionnaire d'utilisateurs <br>"
                                 " <b>\"gest_user\"</b> si vous disposez des droits "
                                 " <b> administrateur </b> ."),
                                 0,0,0,1);
        ret = 1;
        }
     if (ret==1)   return;
     ret = QMessageBox::warning (this,"Annuaire",
                                 tr("ATTENTION ! L'effacement de cette fiche\n"
                                 "est définitif.\n Soyez sûr de cette action."),
                                 tr("&Effacer"),tr("&Ne Rien Faire"),0,1);
     if (ret==1)   return;
     EraseRecord(pCMyQListViewItem);
     QString num;
     text_Label_Status->setText(num.sprintf(tr("Fiche N° %s effacée."), (const char*) pCMyQListViewItem->m_ExData));
     InitAllList(tr("Toutes Spécialités"));
     InitComboSpec();
     if (listBoxChoixNom->childCount())
        {listBoxChoixNom->setCurrentItem(0);
         listBoxChoixNom->setSelected ( listBoxChoixNom->currentItem(), TRUE) ;
         listBoxChoixNom_currentChanged( listBoxChoixNom->currentItem() );
        }
    }
}

//--------------------------------- EraseRecord ----------------------------------------------------------------------
void Praticien_Dlg::EraseRecord( CMyQListViewItem* pCMyQListViewItem)
{if (m_DataBase==0)                                              return ;
 if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return ;

 QString requete("DELETE FROM ");
 requete += G_pCApp->m_INTERVENANTS_TBL_NAME + " WHERE " + G_pCApp->m_INTERVENANTS_PK + "='" + pCMyQListViewItem->m_ExData + "'";
 QSqlQuery* pSqlQuery = new QSqlQuery(requete, m_DataBase);
 if (pSqlQuery) delete pSqlQuery ;
 m_DataBase->close();
}

//--------------------------------- FormToDisk------------------------------------------------------------------------
// ACTION: enregistre la fiche courante dans la base:
// ENTREE: rec_num: cle primaire de l'enregistrement: si -1 il faut en ajouter un sino il faut mettre à jour
CMyQListViewItem* Praticien_Dlg::FormToDisk( CMyQListViewItem* pCMyQListViewItem )
{   QString requete;
    G_pCApp->GotoDebug();
    //................ si le champ obligatoire nom est vide .................................
    //                 cassos après avertissement
    if (lineEdit_Nom->text().stripWhiteSpace()=="")
        {QMessageBox::critical(this,"Annuaire",
                               tr("Le champ « Nom » ne peut être  vide !!!\n"
                                  "Veuillez le compléter avant de\n"
                                  "créer une nouvelle fiche."));
         return 0;
        }
     //................ si le champ specialite est vide .....................................
     //                        y mettre "Divers"
    if (comboBox_Specialite->lineEdit()->text().stripWhiteSpace()=="") comboBox_Specialite->lineEdit()->setText("Divers");
    //................... creer un GUID pour si creation d'une fiche .........................
    QString guid = G_pCApp->GUID_Create();
    //................... CREATION D'UNE FICHE ..............................................
    if ( pCMyQListViewItem == 0)
       {
        requete  = "INSERT INTO ";
        requete +=  G_pCApp->m_INTERVENANTS_TBL_NAME        + " ("
                  + G_pCApp->m_INTERVENANTS_NOM             + ","        // 0
                  + G_pCApp->m_INTERVENANTS_PRENOM          + ","        // 1
                  + G_pCApp->m_INTERVENANTS_ADRESSE         + ","        // 2
                  + G_pCApp->m_INTERVENANTS_CODE_POST       + ","        // 3
                  + G_pCApp->m_INTERVENANTS_VILLE           + ","        // 4
                  + G_pCApp->m_INTERVENANTS_TEL_1           + ","        // 5
                  + G_pCApp->m_INTERVENANTS_TEL_2           + ","        // 6
                  + G_pCApp->m_INTERVENANTS_TEL_3           + ","        // 7
                  + G_pCApp->m_INTERVENANTS_EMAIL           + ","        // 8
                  + G_pCApp->m_INTERVENANTS_NOTE            + ","        // 9
                  + G_pCApp->m_INTERVENANTS_QUALITE         + ","        // 10
                  + G_pCApp->m_INTERVENANTS_TITRE           + ","        // 11
                  + G_pCApp->m_INTERVENANTS_TEL_ABR_1       + ","        // 12
                  + G_pCApp->m_INTERVENANTS_TEL_ABR_2       + ","        // 13
                  + G_pCApp->m_INTERVENANTS_TEL_ABR_3       + ","        // 14
                  + G_pCApp->m_INTERVENANTS_TEL_TYPE_1      + ","        // 15
                  + G_pCApp->m_INTERVENANTS_TEL_TYPE_2      + ","        // 16
                  + G_pCApp->m_INTERVENANTS_TEL_TYPE_3      + ","        // 17
                  + G_pCApp->m_INTERVENANTS_SEXE            + ","        // 18

                  + G_pCApp->m_INTERVENANTS_GUID            + ") VALUES ";

        requete +=  "('" + lineEdit_Nom->text().replace("'","\\'")                     + "', '";       //    0
        requete +=         lineEdit_Prenom->text().replace("'","\\'")                  + "', '";       //    1
        requete +=         textEdit_Rue->text().replace("'","\\'")                     + "', '";       //    2
        requete +=         lineEdit_CodePostal->text()                                 + "', '";       //    3
        requete +=         lineEdit_Ville->text().replace("'","\\'")                   + "', '";       //    4
        requete +=         lineEdit_Tel_1->text()                                      + "', '";       //    5
        requete +=         lineEdit_Tel_2->text()                                      + "', '";       //    6
        requete +=         lineEdit_Tel_3->text()                                      + "', '";       //    7
        requete +=         lineEdit_Email->text()                                      + "', '";       //    8
        requete +=         textEdit_Note->text().replace("'","\\'")                    + "', '";       //    9
        requete +=         comboBox_Specialite->lineEdit()->text()                     + "', '";       //    10
        requete +=         lineEdit_Titre->text().replace("'","\\'")                   + "', '";       //    11
        requete +=         lineEdit_Code_1->text()                                     + "', '";       //    12
        requete +=         lineEdit_Code_2->text()                                     + "', '";       //    13
        requete +=         lineEdit_Code_3->text()                                     + "', '";       //    14

        requete +=         comboBoxTelTyp_1->lineEdit()->text().replace("'","\\'")     + "', '";       //    15
        requete +=         comboBoxTelTyp_2->lineEdit()->text().replace("'","\\'")     + "', '";       //    16
        requete +=         comboBoxTelTyp_3->lineEdit()->text().replace("'","\\'")     + "', '";       //    17
        QString sex = "M"; if (comboBoxSexe->currentText()!=tr("Masculin"))  sex = "F";
        requete +=         sex                                                         + "', '";       //    18

        requete +=         guid                                     + "')  ";
       }
    //................... MIS A JOUR D'UNE FICHE ..............................................
    else
       {requete  = "UPDATE ";
        requete += G_pCApp->m_INTERVENANTS_TBL_NAME      + " SET ";
        requete += G_pCApp->m_INTERVENANTS_NOM           + " = '"    + lineEdit_Nom->text().replace("'","\\'")                  + "', ";
        requete += G_pCApp->m_INTERVENANTS_PRENOM        + " = '"    + lineEdit_Prenom->text().replace("'","\\'")               + "', ";
        requete += G_pCApp->m_INTERVENANTS_ADRESSE       + " = '"    + textEdit_Rue->text().replace("'","\\'")                  + "', ";
        requete += G_pCApp->m_INTERVENANTS_CODE_POST     + " = '"    + lineEdit_CodePostal->text()                              + "', ";
        requete += G_pCApp->m_INTERVENANTS_VILLE         + " = '"    + lineEdit_Ville->text().replace("'","\\'")                + "', ";
        requete += G_pCApp->m_INTERVENANTS_TEL_1         + " = '"    + lineEdit_Tel_1->text()                                   + "', ";
        requete += G_pCApp->m_INTERVENANTS_TEL_2         + " = '"    + lineEdit_Tel_2->text()                                   + "', ";
        requete += G_pCApp->m_INTERVENANTS_TEL_3         + " = '"    + lineEdit_Tel_3->text()                                   + "', ";
        requete += G_pCApp->m_INTERVENANTS_EMAIL         + " = '"    + lineEdit_Email->text()                                   + "', ";
        requete += G_pCApp->m_INTERVENANTS_NOTE          + " = '"    + textEdit_Note->text().replace("'","\\'")                 + "', ";
        requete += G_pCApp->m_INTERVENANTS_QUALITE       + " = '"    + comboBox_Specialite->lineEdit()->text()                  + "', ";
        requete += G_pCApp->m_INTERVENANTS_TITRE         + " = '"    + lineEdit_Titre->text().replace("'","\\'")                + "', ";
        requete += G_pCApp->m_INTERVENANTS_TEL_ABR_1     + " = '"    + lineEdit_Code_1->text()                                  + "', ";
        requete += G_pCApp->m_INTERVENANTS_TEL_ABR_2     + " = '"    + lineEdit_Code_2->text()                                  + "', ";
        requete += G_pCApp->m_INTERVENANTS_TEL_ABR_3     + " = '"    + lineEdit_Code_3->text()                                  + "', ";

        requete += G_pCApp->m_INTERVENANTS_TEL_TYPE_1    + " = '"    + comboBoxTelTyp_1->lineEdit()->text().replace("'","\\'")  + "', ";
        requete += G_pCApp->m_INTERVENANTS_TEL_TYPE_2    + " = '"    + comboBoxTelTyp_2->lineEdit()->text().replace("'","\\'")  + "', ";
        requete += G_pCApp->m_INTERVENANTS_TEL_TYPE_3    + " = '"    + comboBoxTelTyp_3->lineEdit()->text().replace("'","\\'")  + "', ";
        QString sex = "M"; if (comboBoxSexe->currentText()!=tr("Masculin"))  sex = "F";
        requete += G_pCApp->m_INTERVENANTS_SEXE          + " = '"    + sex                                                      + "'  ";

        requete += "WHERE " + G_pCApp->m_INTERVENANTS_PK + " ='" + pCMyQListViewItem->m_ExData +"'";
       }
    if (m_DataBase==0)                                              return 0;
    if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return 0;

    //.................. Executer la requete ...............................................
    QSqlQuery query (requete, m_DataBase);
    G_pCApp->OutSQL_error( query, 0, requete );
    //.................. si creation recuperer numero d'enregistrement .....................
    if (pCMyQListViewItem == 0)
       {requete  = "SELECT ";
        requete += G_pCApp->m_INTERVENANTS_PK     + ", " +
                   G_pCApp->m_INTERVENANTS_NOM    + ", " +
                   G_pCApp->m_INTERVENANTS_PRENOM + "  " +
                   " FROM " + G_pCApp->m_INTERVENANTS_TBL_NAME + " WHERE ";
        requete += G_pCApp->m_INTERVENANTS_GUID   + " = '" + guid + "'";
        query.exec(requete );
        if (query.isActive() && query.next())
           { pCMyQListViewItem = new CMyQListViewItem( listBoxChoixNom,
                                                       Utf8_Query(query,0),
                                                       Utf8_Query(query,1) + " " + Utf8_Query(query,2));
           } //en dif (pSqlQuery->isActive())
       } //end if (rec_num == -1L)
    m_DataBase->close();
    return pCMyQListViewItem;
}

//--------------------------------- listBoxChoixNom_currentChanged -------------------------------------------------------
void Praticien_Dlg::listBoxChoixNom_currentChanged( QListViewItem *pQListViewItem )
{CMyQListViewItem* pCMyQListViewItem = (CMyQListViewItem*)pQListViewItem;
 if (pCMyQListViewItem ==0 ) return;
 ItemToForm(pCMyQListViewItem);
 listBoxChoixNom->ensureItemVisible ( pCMyQListViewItem );
 QString num;
 text_Label_Status->setText(num.sprintf(tr("Fiche N° %s sélectionnée."), (const char*) pCMyQListViewItem->m_ExData));
}

//--------------------------------- EditAutoLocatorChanged -------------------------------------------------------
void Praticien_Dlg::EditAutoLocatorChanged( QEvent * )
{QString qstr(lineEditAutoLocator->text());
 QListViewItem *pQListViewItem = listBoxChoixNom->findItem ( qstr, 0, Qt::BeginsWith );
 if (pQListViewItem)
    {listBoxChoixNom->setCurrentItem(pQListViewItem);
    }
}

//--------------------------------- OnComboSpecSlot -------------------------------------------------------
void Praticien_Dlg::OnComboSpecSlot( const QString & qstr )
{InitAllList(qstr);
 ClearSaisie();
 if (listBoxChoixNom->childCount())
     {listBoxChoixNom->setCurrentItem(0);
      listBoxChoixNom->setSelected ( listBoxChoixNom->currentItem(), TRUE) ;
      listBoxChoixNom_currentChanged( listBoxChoixNom->currentItem() );
     }
}

//--------------------------------- InitAllList ------------------------------------------------------------
void Praticien_Dlg::InitAllList( const QString & qstr)
{ //................. Preparer la requete .................................
  QString requete("");
  requete += "SELECT "     + G_pCApp->m_INTERVENANTS_QUALITE     + ","
                           + G_pCApp->m_INTERVENANTS_PK          + ","
                           + G_pCApp->m_INTERVENANTS_NOM         + ","
                           + G_pCApp->m_INTERVENANTS_PRENOM      +
                           " FROM ";
  if (qstr == tr("Toutes Spécialités") || qstr == "")
     {
      requete    += G_pCApp->m_INTERVENANTS_TBL_NAME + " ORDER BY "   + G_pCApp->m_INTERVENANTS_NOM;
      m_ListState = LIST_COMPLETE;
     }
  else
     {requete    += G_pCApp->m_INTERVENANTS_TBL_NAME + " WHERE " + G_pCApp->m_INTERVENANTS_QUALITE + " ='";
      requete    += qstr + "' ORDER BY " + G_pCApp->m_INTERVENANTS_NOM;
      m_ListState = LIST_COMPLETE+1;
     }

  if (IsThisValueInComboBox(comboBoxSpec,        tr( "Toutes Spécialités"))==-1) comboBoxSpec->insertItem (tr("Toutes Spécialités"));
  if (m_DataBase==0)                                              return ;
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return ;

  QSqlQuery* pSqlQuery = new QSqlQuery(requete , m_DataBase );
  //................ scanner les enregistrements ..........................
  //                 pour remplir le tableau d'indexs
  int i = 0;
  if (pSqlQuery && pSqlQuery->isActive())
     {listBoxChoixNom->clear();

      while (pSqlQuery->next())
        { new CMyQListViewItem( listBoxChoixNom,
                                pSqlQuery->value(1).toString(),
                                pSqlQuery->value(2).toString() + " " + pSqlQuery->value(3).toString());
          QString toAppend = pSqlQuery->value(0).toString().stripWhiteSpace();
          if (IsThisValueInComboBox(comboBoxSpec,        toAppend)==-1) comboBoxSpec->insertItem (toAppend);
          if (IsThisValueInComboBox(comboBox_Specialite, toAppend)==-1) comboBox_Specialite->insertItem (toAppend);
          i++;
        } //end while (pSqlQuery->next())
     } //end if (pSqlQuery && pSqlQuery->isActive())
  G_pCApp->OutSQL_error( *pSqlQuery, 0, requete);
  if (pSqlQuery) delete  pSqlQuery;
  if (i) listBoxChoixNom->setCurrentItem ( listBoxChoixNom->firstChild() );
  if (m_ListState == LIST_COMPLETE) m_NbRec = i;
  QString qstr1;
  qstr1.sprintf(tr("Trouvé %i sur %i"), i, m_NbRec);
  textLabel_StateList->setText(qstr1);
  m_DataBase->close();
  comboBoxSpec->listBox()->sort ();
  comboBox_Specialite->listBox()->sort ();

}

//--------------------------------- InitComboSpec ------------------------------------------------------------
//  ACTION: parcoure la liste d'index et initialise le combobox avec toutes les valeurs trouvées de specialités
//          Il ne faut pas utiliser cette fonction si la liste n'est pas complete donc l'utiliser apres
//          appel à la fonction: InitAllList("Toutes Spécialités");

void Praticien_Dlg::InitComboSpec()
{ if (m_DataBase==0)                                              return ;
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return ;

  QString requete("");
  requete    += "SELECT "     + G_pCApp->m_INTERVENANTS_QUALITE      + " FROM ";
  requete    += G_pCApp->m_INTERVENANTS_TBL_NAME + " ORDER BY "      + G_pCApp->m_INTERVENANTS_QUALITE;
  QSqlQuery* pSqlQuery = new QSqlQuery(requete , m_DataBase );

  //................ scanner les enregistrements ..........................
  //                 pour remplir le tableau d'indexs
  comboBoxSpec->clear();
  comboBox_Specialite->clear();
  comboBoxSpec->insertItem(tr("Toutes Spécialités"));
  if (pSqlQuery && pSqlQuery->isActive())
     {while (pSqlQuery->next())
        {QString toAppend = pSqlQuery->value(0).toString().stripWhiteSpace();
          if (toAppend.length())
             {if (IsThisValueInComboBox(comboBoxSpec,        toAppend)==-1) comboBoxSpec->insertItem (toAppend);
              if (IsThisValueInComboBox(comboBox_Specialite, toAppend)==-1) comboBox_Specialite->insertItem (toAppend);
             }
        } //end while (pSqlQuery->next())
     }
  if (pSqlQuery) delete  pSqlQuery;
  comboBoxSpec->listBox()->sort ();
  comboBox_Specialite->listBox()->sort ();
  m_DataBase->close();
}

//--------------------------------- IsThisValueInComboBox ------------------------------------------------------------
int Praticien_Dlg::IsThisValueInComboBox(QComboBox *pQComboBox, const QString& value)
{
 int nb = pQComboBox->count();
 for (int i=0; i < nb; ++i)
     {if (pQComboBox->text(i) == value ) return i;
     }
 return -1;
 }

//--------------------------------- listBoxChoixNom_doubleClicked ------------------------------------------------------------
void Praticien_Dlg::listBoxChoixNom_doubleClicked( QListViewItem *pQListViewItem )
{CMyQListViewItem* pCMyQListViewItem = (CMyQListViewItem*)pQListViewItem;
 if (pCMyQListViewItem ==0 ) return;

 int nb_arg = Global_pCMedinTuxApp->argc();                 // 0 = path programme   1 = fichier patient
 if (nb_arg >= 2)
    {QString path ( Global_pCMedinTuxApp->argv()[ 1 ] );
     if (Global_pCMedinTuxApp->argv()[ 2 ]==QString("Record"))
        {QString num_rec =     pCMyQListViewItem->m_ExData                    +"|"+
                               lineEdit_Nom->text()                           +"|"+
                               lineEdit_Prenom->text()                        +"|"+
                               comboBox_Specialite->currentText () ;
         QFile file( path);
         if ( !file.open( IO_WriteOnly ) )    return;
         QTextStream ts( &file );
         ts << num_rec;
         accept();

        }
    }
}

//--------------------------------- pushButtonOK_clicked ------------------------------------------------------------
void Praticien_Dlg::pushButtonOK_clicked()
{QListViewItem *pQListViewItem = listBoxChoixNom->currentItem();
 listBoxChoixNom_doubleClicked(pQListViewItem);
 accept();
}


//--------------------------------- pushButtonOK_pressed ------------------------------------------------------------
void Praticien_Dlg::pushButtonOK_pressed()
{pushButtonOK_clicked();
}


//--------------------------------- pushButtonOK_released ------------------------------------------------------------
void Praticien_Dlg::pushButtonOK_released()
{pushButtonOK_clicked();
}


void Praticien_Dlg::listBoxChoixNom_returnPressed( QListViewItem * )
{pushButtonOK_clicked();
}
