/****************************************************************************
** 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.
*****************************************************************************/

//=============================================== DEFINE =========================================================


#define Min(a, b)             ((a) < (b) ? (a) : (b))
#define Max(a, b)             ((a) > (b) ? (a) : (b))


//=============================================== IMPLEMENTTION =====================================================

//--------------------------------- Init ------------------------------------------------------------------------------
void FormRubObservation::init()
{m_IsModifiable =  0;
 m_pMyEditText  =  0;
 m_LastRub      = -1;
 pushButtonSave->setIconSet           (Theme::getIconSave() );
 pushButtonPrint->setIconSet          (Theme::getIconPrint() );
 connect(textLabel_NbRub, SIGNAL( pressed() ), this, SLOT( On_buttonDragClicked() ));
}

//--------------------------------- On_buttonDragClicked ------------------------------------------------------
// connect(textLabel_NbRub, SIGNAL( clicked() ), this, SLOT( On_buttonDragClicked() ));
//   virtual void          On_buttonDragClicked();
void  FormRubObservation::On_buttonDragClicked() 
{   RUBREC_LIST::iterator it = Current_RubList_Iterator();
    if ( it != m_pRubList->end() ) (*it).dragRubrique(this);
}

//--------------------------------- SetModifiableState -----------------------------------------------------------------------
void  FormRubObservation::SetModifiableState(int state)
{m_IsModifiable = state;
 if (m_IsModifiable)
    {pushButtonSave->show();
     pushButtonRubDateChange->show();
     pushButtonDelete->show();
    }
 else
    {pushButtonSave->hide();
     pushButtonRubDateChange->hide();
     pushButtonDelete->hide();
    }
}

//--------------------------------- InitText -------------------------------------------------------------------------
// ACTION: rattache à la variable membre: MyEditText *m_pMyEditText  l'editeur de texte passé en entrée
//         et initialise cet editeur sur les valeurs adéquates
//         Il est imperatif d'apeler cette fonction apres le constructeur de: FormRubObservation
void FormRubObservation::InitText(MyEditText *pMyEditText)
{if (pMyEditText==0)     return;
 m_pMyEditText = pMyEditText;
 m_pMyEditText->setGeometry (QRect  (0,100,100,400));
 m_pMyEditText->setTextFormat(RichText);
 //m_pMyEditText->mimeSourceFactory()->setImage( "myimage", QImage(Ez_edit_xpm) );
}

//--------------------------------- FormPatientList_destroyed -------------------------------------------------------------
void FormRubObservation::FormPatientList_destroyed( QObject * )
{//if (m_pMyEditText!=0) m_pMyEditText->mimeSourceFactory()->setData( "myimage", 0 );
}

//--------------------------------- SetData--------------------------------------------------------------------------------
int FormRubObservation::SetData()
{QString qstr;
 if (m_pCMoteurBase==0) return 0;
 if (m_ID_Doss!="")
    {
     QVariant qvar;
     m_pCMoteurBase->GetFieldValue(m_pCMoteurBase->m_DOSS_IDENT_TBL_NAME,
                                   m_pCMoteurBase->m_DOSS_IDENT_NSS,
                                   m_pCMoteurBase->m_DOSS_IDENT_REF_PK ,
                                   m_ID_Doss,
                                   &qvar);
     QDate qDteNss = qvar.toDate();
     textLabel_Age->setText( m_pCMoteurBase->CalculeDiffAge(&qDteNss));
    }
 else
    {textLabel_Age->setText( "");
    }
 //................. mettre à jour le texte ............................
 int nb = initComboListObservation();
 if (nb>0)
    {comboBox_RubName->setCurrentItem (nb-1);
     comboBox_RubName_activated( nb-1);
     if (m_pMyEditText!=0) {m_pMyEditText->m_State = 1;
                            m_pMyEditText->show();
                           }
     show();
    }
 else
    {if (m_pMyEditText!=0){m_pMyEditText->m_State = 0;
                           m_pMyEditText->hide();
                           textLabel_UserName->setText("");
                           m_pMyEditText->setText("");
                          }
     hide();
    }
 textLabel_NbRub->setText(qstr.setNum(nb));
 return nb;
}

//--------------------------------- initComboListObservation -------------------------------------------------------------
/*! \brief initialise le combo des observations.
 *  \return nombre d'observations ajoutées.
 */
long  FormRubObservation::initComboListObservation(void)
{return m_pCMoteurBase->initConboBoxWithRubList(m_pRubList, comboBox_RubName, QString::number(TYP_OBSERVATION));
}

//--------------------------------- comboBox_RubName_highlighted -------------------------------------------------------------
void FormRubObservation::comboBox_RubName_highlighted( int item )
{comboBox_RubName_activated(item);
}


//--------------------------------- comboBox_RubName_activated -------------------------------------------------------------
void FormRubObservation::comboBox_RubName_activated( int item)
{CPrtQListBoxItem* pCPrtQListBoxItem  = (CPrtQListBoxItem*) comboBox_RubName->listBox()->item ( item );
 if (pCPrtQListBoxItem == 0) return;
 int     id  =  pCPrtQListBoxItem->GetPk().toInt();

 QByteArray          data;
 char                *ptr = 0;
 RUBREC_LIST::iterator it = m_pRubList->at(id);
 //........................... si rubrique qui etait avant celle a afficher, a ete modifiée ................................................
 //                            replacer son contenu dans la liste des rubriques avant d'afficher la nouvelle
 if (m_pMyEditText && m_pMyEditText->isModified() && m_LastRub != -1)
    {SaveTextInRubList();
    }
 //........................... retirer le texte de la nouvelle rubrique a afficher ..............................
 //
 int ret   = m_pCMoteurBase->GetDataFromRubList(data, it);
 m_LastRub = id;                   // c'est maintenant la dernière affichée
 int     f = 0;
 if (ret == RUB_READ_ON_DISK)      // en fait cela veut dire que ça été lu sur le disque
    {ptr        = data.data();
     long len   = data.size()-4;
     if (ptr && len>6)
        {QString stringDST;
         if (strncmp(ptr, "<html>", 6))
            {CHtmlTools::RtfToQtextEdit_HTML(ptr+4, len, stringDST,1);
             if (m_pMyEditText!=0)
                {m_pMyEditText->setText(stringDST);
                 m_pMyEditText->setModified (FALSE);
                }
            }
         else
            {if (m_pMyEditText!=0)
                {m_pMyEditText->setText( ptr );
                 m_pMyEditText->setModified (FALSE);
               }
            }
         f = 1;
        }
    }
 else if (ret == RUB_READ_IN_LIST)   // en fait cela veut dire que ça été lu dans les données de liste
    {ptr      = data.data();
     if (ptr && m_pMyEditText!=0)
        {m_pMyEditText->setText( ptr );
         m_pMyEditText->setModified (FALSE);
        }
     f = 1;
    }
 //........................ régler droits utilisateurs ......................................................................
 QString user              = (*it).m_User;
 QString doc_sign_user     = (*it).m_SignUser;

 if (G_pCApp->m_User != doc_sign_user)  // si l'utilisateur actuel n'est pas le même que le signataire du document vérifier les droits
    {QString friend_droits     = G_pCApp->m_pCMoteurBase->PermsUserIsThisUserFriendFromName(  doc_sign_user , G_pCApp->m_User);
     if (G_pCApp->IsThisDroitExist(friend_droits, "obv")) {                                                                 pushButtonDelete->setEnabled(TRUE); pushButtonRubDateChange->setIconSet(Theme::getIconChangeDate() );}
     else                                                      { m_pMyEditText->setText(G_pCApp->m_MessVisuDocNotPossible); pushButtonDelete->setEnabled(FALSE);pushButtonRubDateChange->setIconSet(Theme::getIconCadenas() );}
     if (G_pCApp->IsThisDroitExist(friend_droits, "obc")) { m_pMyEditText->setReadOnly (FALSE );pushButtonDelete->setEnabled(TRUE);pushButtonRubDateChange->setIconSet(Theme::getIconChangeDate() );}
     else                                                      { m_pMyEditText->setReadOnly (TRUE ); pushButtonDelete->setEnabled(FALSE);pushButtonRubDateChange->setIconSet(Theme::getIconCadenas() );}
     if (G_pCApp->IsThisDroitExist(friend_droits, "obp")) { pushButtonPrint->setEnabled(TRUE);}
     else                                                      { pushButtonPrint->setEnabled(FALSE);}
    }
 else
    {m_pMyEditText->setReadOnly (FALSE );pushButtonDelete->setEnabled(TRUE); pushButtonPrint->setEnabled(TRUE);pushButtonRubDateChange->setIconSet(Theme::getIconChangeDate() );
    }
 textLabel_UserName->setText(user + "::" + doc_sign_user);

 if ((*it).m_State == RUB_IS_TO_DELETE) {pushButtonDelete->setIconSet (Theme::getIconIsDeleted() ); pushButtonDelete->setDown(TRUE);}
 else                                   {pushButtonDelete->setIconSet (Theme::getIconDelete() );    pushButtonDelete->setDown(FALSE);}
 if (m_pMyEditText!=0 && f==0) m_pMyEditText->setText("");
}

//--------------------------------- IfModified_SaveInRubList -------------------------------------------------------------
int FormRubObservation::IfModified_SaveInRubList()
{//........................... si rubrique qui etait avant celle a afficher, a ete modifiée ................................................
 //                            replacer son contenu dans la liste des rubriques avant d'afficher la nouvelle
 if (m_IsModifiable && m_pMyEditText && m_pMyEditText->isModified()  && m_LastRub != -1)
    {SaveTextInRubList();
     return TRUE;
    }
 return FALSE;
}

//--------------------------------- pushButtonDelete_clicked -------------------------------------------------------------
void FormRubObservation::pushButtonDelete_clicked()
{
 if (m_IsModifiable==0) return;

 CPrtQListBoxItem* pCPrtQListBoxItem  = (CPrtQListBoxItem*) comboBox_RubName->listBox()->item ( comboBox_RubName->currentItem ()  );
 if (!pCPrtQListBoxItem) return;
 int id  =  pCPrtQListBoxItem->GetPk().toInt();

 RUBREC_LIST::iterator it = m_pRubList->at(id);
 //........................... si rubrique qui etait avant celle a afficher, a ete modifiée ................................................
 //                            replacer son contenu dans la liste des rubriques avant d'afficher la nouvelle
 if ((*it).m_State & RUB_IS_TO_DELETE)
    {m_pCMoteurBase->RubList_SetItemNotDeleted(m_pRubList, id);
    }
 else
    {m_pCMoteurBase->RubList_SetItemDeleted(m_pRubList, id);
    }
 if ((*it).m_State == RUB_IS_TO_DELETE) {pushButtonDelete->setIconSet (Theme::getIconIsDeleted() ); pushButtonDelete->setDown(TRUE);}
 else                                   {pushButtonDelete->setIconSet (Theme::getIconDelete() );    pushButtonDelete->setDown(FALSE);}
}

//--------------------------------- pushButtonSave_clicked -------------------------------------------------------------
void FormRubObservation::pushButtonSave_clicked()
{if (m_IsModifiable) emit Sign_SaveButtonClicked();                                           // et voila
}

//--------------------------------- Current_RubList_ID -------------------------------------------------------------
int FormRubObservation::Current_RubList_ID()
{CPrtQListBoxItem* pCPrtQListBoxItem  = (CPrtQListBoxItem*) comboBox_RubName->listBox()->item ( comboBox_RubName->currentItem ()  );
 if (pCPrtQListBoxItem) return pCPrtQListBoxItem->GetPk().toInt();
 return -1;
}

//--------------------------------- Current_RubList_Iterator -------------------------------------------------------------
RUBREC_LIST::iterator FormRubObservation::Current_RubList_Iterator()
{int id = Current_RubList_ID();
 if (id==-1) return  m_pRubList->end();
             return  m_pRubList->at(id);
}

//--------------------------------- SetCurentDocByPrimkey -------------------------------------------------------------
int FormRubObservation::SetCurentDocByPrimkey(const QString &primKey)
{QListBox *pQListBox = comboBox_RubName->listBox();
 int last            = comboBox_RubName->count ();
 int i;
 for (i=0; i<last; i++)
     {CPrtQListBoxItem* pCPrtQListBoxItem  = (CPrtQListBoxItem*) pQListBox->item ( i );
     if (pCPrtQListBoxItem->GetUser() == primKey)
        {comboBox_RubName->setCurrentItem(i);
         comboBox_RubName_activated(i);
         return i;
        }
     }
 return -1; // pas trouvé
}

//--------------------------------- pushButtonRubDateChange_clicked -------------------------------------------------------------
void FormRubObservation::pushButtonRubDateChange_clicked()
{if (m_IsModifiable==0)                  return;
 if (m_pMyEditText->isReadOnly())        return;

 CPrtQListBoxItem* pCPrtQListBoxItem  = (CPrtQListBoxItem*) comboBox_RubName->listBox()->item ( comboBox_RubName->currentItem ()  );
 if (!pCPrtQListBoxItem)                 return;

 RUBREC_LIST::iterator it   =  m_pRubList->at(pCPrtQListBoxItem->GetPk().toInt());
 DlgDateNom *dlg = new DlgDateNom(this,"DateNOm_Dlg",TRUE);        // TRUE Pour modal
 if (dlg ==0)                            return ;
 dlg->initDialog( &(*it).m_Date, &(*it).m_Libelle, &(*it).m_SubType);

 if ( dlg->exec() == QDialog::Accepted ) 
    { //................... remettre à jour le comboBox ................................
      pCPrtQListBoxItem->SetType((*it).m_Date);
      pCPrtQListBoxItem->SetDate((*it).m_Date);
      pCPrtQListBoxItem->setText((*it).m_Date.left(10) + " " +(*it).m_Libelle );
      //................... mettre le document en modified (en replaçant les data ds rubrique liste) ......................
      if (m_pMyEditText && m_LastRub != -1)
         {SaveTextInRubList();
         }
    }
 delete dlg;
}

//--------------------------------- SetRubDateName -------------------------------------------------------------
void FormRubObservation::SetRubDateName( const QString &name, const QString &date )
{
 if (m_IsModifiable==0)                   return;

 CPrtQListBoxItem* pCPrtQListBoxItem  = (CPrtQListBoxItem*) comboBox_RubName->listBox()->item ( comboBox_RubName->currentItem ()  );
 if (!pCPrtQListBoxItem)                  return;

 RUBREC_LIST::iterator it   =  m_pRubList->at(pCPrtQListBoxItem->GetPk().toInt());
 //................... remettre à jour les valeurs de la liste ................................
 if (name.length()<=0 && date.length()<19) return; //2004-03-10 19:21:19
 if (name.length()>0)   (*it).m_Libelle = name;
 if (date.length()==19) (*it).m_Date    = date;

 //................... remettre à jour le comboBox ................................
  pCPrtQListBoxItem->SetType((*it).m_Date);
 pCPrtQListBoxItem->SetDate((*it).m_Date);
 pCPrtQListBoxItem->setText((*it).m_Date.left(10) + " " +(*it).m_Libelle );
 //................... mettre le document en modified (en replaçant les data ds rubrique liste) ......................
 if (m_pMyEditText && m_LastRub != -1)
    {SaveTextInRubList();
    }
}

//--------------------------------- GetRubDateName -------------------------------------------------------------
void FormRubObservation::GetRubDateName( QString &name, QString &date )
{CPrtQListBoxItem* pCPrtQListBoxItem  = (CPrtQListBoxItem*) comboBox_RubName->listBox()->item ( comboBox_RubName->currentItem ()  );
 if (!pCPrtQListBoxItem)             return;

 RUBREC_LIST::iterator it = m_pRubList->at(pCPrtQListBoxItem->GetPk().toInt());
 date = (*it).m_Date;
 name = (*it).m_Libelle;
}

//--------------------------------- SaveTextInRubList -------------------------------------------------------------
void FormRubObservation::SaveTextInRubList()
{if (m_IsModifiable==0) return;
  //if (m_pMyEditText && m_LastRub != -1)
    {QString       txt = m_pMyEditText->text();
     //CHtmlTools::setTextDefaultAtribut(txt, "background",    edit->m_PathImage);
     CHtmlTools::setTextDefaultAtribut(txt, "text",              m_pMyEditText->m_DefaultTextColor);
     CHtmlTools::setTextDefaultAtribut(txt, "bgcolor",           m_pMyEditText->m_DefaultBackgroundColor);
     m_pCMoteurBase->ReplaceDataInRubList(txt, m_pRubList, m_LastRub );
    }

}

