/****************************************************************************
** 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 "../../MedinTuxTools/Theme.h"
#define Min(a, b)             ((a) < (b) ? (a) : (b))
#define Max(a, b)             ((a) > (b) ? (a) : (b))

//----------------------------------------- initDialog -----------------------------------------
void Dlg_RDV_Manager::initDialog(CMoteurAgenda *pCMoteurAgenda, RDV_LIST *pRDV_List, RendezVous *pRendezVous, MAP_COLOR *pColorProfils, int mode)
{m_pRDV_List        = pRDV_List;
 m_pCMoteurAgenda   = pCMoteurAgenda;
 m_pRendezVous      = pRendezVous;
 m_pColorProfils    = pColorProfils;
 m_RetPopupItem     = "";
 m_CurrentPopupItem = "";
 m_pQPopupMenu      = 0;
 m_DureeMin         = 5;
 m_DefaultDureeRDV  = 15;
 initComboColorProfils();
 QStringList qstringList;
 //.............................. liste des signataires pour lequel l'utilisateur .......................................
 //                                   est autorisé à prendre des rendez-vous
 G_pCApp->m_pCMoteurBase->PermsUserSignUserListForThisUser(   G_pCApp->m_User, qstringList,  "agc");
 if (G_pCApp->m_User == G_pCApp->m_SignUser)     // si on c'est un signataire et non un autorisé le rajouter en début de liste
    {qstringList.prepend( G_pCApp->m_SignUser);
    }
 comboBox_User->insertStringList ( qstringList );
 RendezVousToDialog();
 connect( lineEdit_Heure, SIGNAL( Sig_FocusOut ()),
           this,     SLOT(   OnOutFocuslineEdit_Heure())
        );
 connect( lineEdit_Duree, SIGNAL( Sig_FocusOut ()),
           this,     SLOT(   OnOutFocuslineEdit_Duree())
        );
 //.............. positionner l'heure du RDV sur le dernier premier libre .....................
 QStringList intervallesList;
 GetIntervallesList(intervallesList);
 if (intervallesList.count()>1 && mode == 1) // que si il y a déjà des Rendez-Vous et mode creation/ajout
    {QTime deb;
     QTime end;
     int duree = Min(m_DefaultDureeRDV, Dlg_RDV_Manager::stringChoixMenuToValue(intervallesList[0], deb, end));
     lineEdit_Duree->setText( QString::number(duree) );
     lineEdit_Heure->setText(deb.toString("hhmm") );
     m_pRendezVous->m_Duree    = duree;
     m_pRendezVous->m_date     = QDateTime (m_pRendezVous->m_date.date(), deb);
     DialogToRendezVous(0);
   }
  pushButtonTypeAppend->setIconSet (Theme::getIconSet("filesave.png"));
  pushButtonTypeDelete->setIconSet (Theme::getIconSet("trashcan_empty.png"));
  pushButton_IdentErase->setIconSet (Theme::getIconSet("Terrain_annule.png"));
  pushButton_OK->setIconSet (Theme::getIconSet("button_Ok.png"));
  pushButton_Annuler->setIconSet (Theme::getIconSet("exit.png"));
  //comboBox_User->setIconSet (Theme::getIconSet("32x32/personal.png"));
}

//----------------------------------------- OnOutFocuslineEdit_Heure -----------------------------------------
void Dlg_RDV_Manager::OnOutFocuslineEdit_Heure()
{VerifyDate();
}

//----------------------------------------- initComboColorProfils -----------------------------------------
void Dlg_RDV_Manager::OnOutFocuslineEdit_Duree()
{VerifyDate();
}

//----------------------------------------- VerifyDate -----------------------------------------------------
int Dlg_RDV_Manager::VerifyDate()
{
 QString   hm = lineEdit_Heure->text();
 int       h  = hm.mid(0,2).toInt();
 int       m  = hm.mid(2,2).toInt();
 QTime tm_inf(h ,m);
 QTime tm_sup = tm_inf.addSecs ( lineEdit_Duree->text().toInt()*60 );
 QString message("");

 RendezVous *pRendezVous;
 for ( pRendezVous    = m_pRDV_List->first(); pRendezVous; pRendezVous = m_pRDV_List->next() )
     { if (pRendezVous != m_pRendezVous) // on se teste pas comme objet courant
          {QTime  cur_Inf = pRendezVous->m_date.time();
           QTime  cur_Sup = cur_Inf.addSecs ( pRendezVous->m_Duree*60 );
           if (tm_inf>=cur_Inf && tm_inf<cur_Sup)
              {message += tr("L'heure de début de ce rendez-vous n'est pas valable\n"
                             "car elle en chevauche une autre.\n");
               break;
              }
          }
     }
 for ( pRendezVous    = m_pRDV_List->first(); pRendezVous; pRendezVous = m_pRDV_List->next() )
     { if (pRendezVous != m_pRendezVous) // on se teste pas comme objet courant
          {QTime  cur_Inf = pRendezVous->m_date.time();
           QTime  cur_Sup = cur_Inf.addSecs ( pRendezVous->m_Duree*60 );
           if (tm_sup>cur_Inf && tm_sup<=cur_Sup)
              {message += tr("L'heure de fin de ce rendez-vous n'est pas valable\n"
                             "car elle en chevauche une autre.\n");
	       break;
              }
          }
     }
if (message.length())
   {disconnect( lineEdit_Heure, SIGNAL( Sig_FocusOut( )),
                               0,               0 );
    disconnect( lineEdit_Duree, SIGNAL( Sig_FocusOut( )),
                               0,               0 );
    QMessageBox::information( this, tr("Début de rendez-vous non valable"),
                                        message ,
                                        tr("&OK"), 0, 0,
                                        1, 1 );
    connect( lineEdit_Heure, SIGNAL( Sig_FocusOut ()),
                   this,     SLOT(   OnOutFocuslineEdit_Heure())
        );
    connect( lineEdit_Duree, SIGNAL( Sig_FocusOut ()),
                   this,     SLOT(   OnOutFocuslineEdit_Duree())
        );
     return 0;
   }
 return 1;
}

//----------------------------------------- initComboColorProfils -----------------------------------------
void Dlg_RDV_Manager::initComboColorProfils()
{comboBox_RdvType->clear();
 MAP_COLOR::Iterator it;
 for ( it = m_pColorProfils->begin(); it != m_pColorProfils->end(); ++it )
     {QString value = it.key().latin1();
      if (value.length()) comboBox_RdvType->insertItem (value);
     }
}

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

//----------------------------------------- comboBox_RdvType_activated -----------------------------------------
void Dlg_RDV_Manager::comboBox_RdvType_activated( const QString &str )
{m_pRendezVous->m_Type = str;
 textLabelColorType->setPaletteBackgroundColor(QColor( (*m_pColorProfils)[str] ) );
 textLabelColorType_2->setPaletteBackgroundColor(QColor( (*m_pColorProfils)[str] ) );
 lineEditTexteType->setText(str);
}

//----------------------------------------- GetBornes -----------------------------------------
int Dlg_RDV_Manager::GetBornes(QTime &borne_inf, QTime &borne_sup)
{QDateTime rdv_inf = m_pRendezVous->m_date;
 QDateTime rdv_sup = m_pRendezVous->m_date.addSecs ( m_pRendezVous->m_Duree*60 ) ;

 QDateTime borneInf (m_pRendezVous->m_date.date(), QTime(0,0));
 QDateTime borneSup (m_pRendezVous->m_date.date(), QTime(23,59));

 RendezVous *pRendezVous;
 for ( pRendezVous   = m_pRDV_List->first(); pRendezVous; pRendezVous = m_pRDV_List->next() )
     { QDateTime  cur_Inf = pRendezVous->m_date;
       QDateTime  cur_Sup = cur_Inf.addSecs ( pRendezVous->m_Duree*60 );
       if (pRendezVous != m_pRendezVous) // on se teste pas comme objet courant
          {if (cur_Inf >= rdv_sup && cur_Inf <= borneSup) borneSup = cur_Inf;   // noter borne superieure
           if (cur_Sup <= rdv_inf && cur_Sup >= borneInf) borneInf = cur_Sup;   // noter borne inferieure
          }
     }
 borne_inf = borneInf.time();
 borne_sup = borneSup.time();
 int n = (borneInf.secsTo(borneSup)/60);
 return  n;
}

//----------------------------------------- GetDureeMaxPossible -----------------------------------------
int Dlg_RDV_Manager::GetDureeMaxPossible()
{QTime borneInf;
 QTime borneSup;
 GetBornes(borneInf, borneSup);
 int n = (m_pRendezVous->m_date.time().secsTo(borneSup)/60);
 return n;
}

//----------------------------------------- GetIntervallesList -----------------------------------------
int Dlg_RDV_Manager::GetIntervallesList(QStringList &intervallesList)
{int           nb = 1;
 int           mn;
 QDateTime rdv_inf = m_pRendezVous->m_date;
 QDateTime rdv_sup = m_pRendezVous->m_date.addSecs ( m_pRendezVous->m_Duree*60 ) ;

 QDateTime lastInf (m_pRendezVous->m_date.date(), QTime(0,0));
 QDateTime lastSup (m_pRendezVous->m_date.date(), QTime(23,59));

 RendezVous *pRendezVous;
 for ( pRendezVous   = m_pRDV_List->first(); pRendezVous; pRendezVous = m_pRDV_List->next() )
     { QDateTime  cur_Inf = pRendezVous->m_date;
       QDateTime  cur_Sup = cur_Inf.addSecs ( pRendezVous->m_Duree*60 );
       mn = (lastInf.secsTo(cur_Inf)/60);
       if (mn>=m_DureeMin )
          {intervallesList.append (lastInf.time().toString(tr("de hh:mm à ")) + cur_Inf.time().toString(tr("hh:mm durée ")) + dureeTosString(mn));
          }
       lastInf = cur_Sup;
       ++nb;
     }
 //........................... dernier intervalle en premier (car le plus ouvent utilisé) ......................................
 mn = (lastInf.secsTo(lastSup)/60);
 if (mn>=m_DureeMin )  // m_DureeMin durée minimum d'un rendez-vous
    {intervallesList.prepend(lastInf.time().toString(tr("de hh:mm à ")) + lastSup.time().toString(tr("hh:mm durée ")) + dureeTosString(mn));
    }
 return nb;
}

//----------------------------------------- dureeTosString -----------------------------------------
QString Dlg_RDV_Manager::dureeTosString(int duree_mn)
{QTime qt( 0, 0);
 qt = qt.addSecs ( duree_mn*60 );
 return qt.toString ( "hh:mm" );
}

//----------------------------------------- RendezVousToDialog -----------------------------------------
void Dlg_RDV_Manager::RendezVousToDialog()
{lineEdit_Nom->setText(m_pRendezVous->m_Nom );
 lineEdit_Premom->setText(m_pRendezVous->m_Prenom );
 lineEdit_Tel->setText(m_pRendezVous->m_Tel );
 textLabel_NumGUID->setText(m_pRendezVous->m_GUID );
 lineEdit_Heure->setText(m_pRendezVous->m_date.time().toString("hhmm") );
 lineEdit_Duree->setText( QString::number(m_pRendezVous->m_Duree) );
 lineEdit_Motif->setText(m_pRendezVous->m_Note );
 lineEdit_RdvPrisPar->setText(m_pRendezVous->m_PrisPar );
 setCaption(tr("Rendez-vous du : ") + m_pRendezVous->m_date.date().toString("ddd dd MMMM yyyy"));
 SetComboBoxOnValue(comboBox_RdvType, m_pRendezVous->m_Type);
 SetComboBoxOnValue(comboBox_User,    m_pRendezVous->m_PrisAvec);
 textLabelColorType->setPaletteBackgroundColor(QColor( (*m_pColorProfils)[comboBox_RdvType->currentText()] ) );
 textLabelColorType_2->setPaletteBackgroundColor(QColor( (*m_pColorProfils)[comboBox_RdvType->currentText()] ) );
 lineEditTexteType->setText(comboBox_RdvType->currentText());
}

//---------------------------------------- stringChoixMenuToValue ---------------------------------------------------------
int Dlg_RDV_Manager::stringChoixMenuToValue(const QString &str, QTime &deb, QTime &end)
{deb  = QTime(str.mid(3 ,2).toInt(), str.mid(6 ,2).toInt());
 end  = QTime(str.mid(11,2).toInt(), str.mid(14,2).toInt());
 return (deb.secsTo(end)/60);
}

//---------------------------------------- pushButtonTypeDelete_clicked ---------------------------------------------------
void Dlg_RDV_Manager::pushButtonTypeDelete_clicked()
{m_pCMoteurAgenda->COL_Delete( comboBox_RdvType->currentText() );
 m_pColorProfils->clear();
 m_pCMoteurAgenda->COL_Get_List(*m_pColorProfils);
 initComboColorProfils();
 SetComboBoxOnValue(comboBox_RdvType, m_pRendezVous->m_Type);
 textLabelColorType->setPaletteBackgroundColor(QColor( (*m_pColorProfils)[comboBox_RdvType->currentText()] ) );
 textLabelColorType_2->setPaletteBackgroundColor(QColor( (*m_pColorProfils)[comboBox_RdvType->currentText()] ) );
 lineEditTexteType->setText(comboBox_RdvType->currentText());
}

//---------------------------------------- pushButtonTypeColor_clicked ---------------------------------------------------
void Dlg_RDV_Manager::pushButtonTypeColor_clicked()
{QColor col =  QColorDialog::getColor ( textLabelColorType->paletteBackgroundColor(), this );
 textLabelColorType->setPaletteBackgroundColor( col );
 textLabelColorType_2->setPaletteBackgroundColor( col );
}

//---------------------------------------- pushButtonTypeAppend_clicked ---------------------------------------------------
void Dlg_RDV_Manager::pushButtonTypeAppend_clicked()
{QString name = lineEditTexteType->text();
 name = name.stripWhiteSpace();
 if (name.length()<=0) return;
 QColor    col = textLabelColorType->paletteBackgroundColor();
 QString color = col.name();
 m_pCMoteurAgenda->COL_Create(name , color) ;
 m_pColorProfils->clear();
 m_pCMoteurAgenda->COL_Get_List(*m_pColorProfils);
 initComboColorProfils();
 SetComboBoxOnValue(comboBox_RdvType, m_pRendezVous->m_Type);
}

//---------------------------------------- pushButtonChoixHeure_clicked ---------------------------------------------------
void Dlg_RDV_Manager::pushButtonChoixHeure_clicked()
{QStringList intervallesList;
 GetIntervallesList(intervallesList);
 QString choix = DoPopupList(intervallesList);
 if (choix == tr("Tout est libre pour ce jour") ) return;
 if (choix.length()==0)                           return;
 QTime deb;
 QTime end;
 int duree = stringChoixMenuToValue(choix, deb, end);
 //............. si espace avant premier RDV ......................
 //              se placer 15 mn avant
 if (deb == QTime(0,0))
    {duree = m_DefaultDureeRDV;
     deb   = end.addSecs (-60 * duree ) ;
    }
 //............. si espace apres dernier RDV ......................
 //              placer duree 15 mn
 else if (end == QTime(23,59))
    {duree = m_DefaultDureeRDV;
    }
else
   {//.............. sinon occuper au maximum tout l'espace restant ...............
    duree = Min(m_DefaultDureeRDV, duree);
   }
 lineEdit_Duree->setText( QString::number(duree) );
 lineEdit_Heure->setText(deb.toString("hhmm") );
 m_pRendezVous->m_Duree    = duree;
 m_pRendezVous->m_date     = QDateTime (m_pRendezVous->m_date.date(), deb);
 DialogToRendezVous(0);
}

//----------------------------------------- comboBox_Duree_activated -----------------------------------------
void Dlg_RDV_Manager::comboBox_Duree_activated( const QString &str )
{DialogToRendezVous(1);
 int duree = GetDureeMaxPossible();
 int   max = duree;
 if  (str != tr("Maximum")) duree = str.toInt();
 if (duree>max) duree = max;
 lineEdit_Duree->setText(QString::number(duree));
 DialogToRendezVous(1);
 RendezVousToDialog();
}

//----------------------------------------- DialogToRendezVous -----------------------------------------
void Dlg_RDV_Manager::DialogToRendezVous(int mode)
{
 QString   hm = lineEdit_Heure->text();
 int       h  = hm.mid(0,2).toInt();
 int       m  = hm.mid(2,2).toInt();

 //............... limiter vers le bas le rendez vous ........................
 QTime tm(h,m);
 QTime borne_inf;
 QTime borne_sup;
 GetBornes(borne_inf, borne_sup);
 if (mode && tm < borne_inf)    tm = borne_inf;

 m_pRendezVous->m_date     = QDateTime (m_pRendezVous->m_date.date(), tm);
 m_pRendezVous->m_Duree    = Min(GetDureeMaxPossible(),lineEdit_Duree->text().toInt());

 m_pRendezVous->m_Nom      = lineEdit_Nom->text( );
 m_pRendezVous->m_Prenom   = lineEdit_Premom->text( );
 m_pRendezVous->m_Tel      = lineEdit_Tel->text( );
 m_pRendezVous->m_GUID     = textLabel_NumGUID->text();

 m_pRendezVous->m_Note     = lineEdit_Motif->text();
 m_pRendezVous->m_PrisAvec = comboBox_User->currentText();
 m_pRendezVous->m_PrisPar  = lineEdit_RdvPrisPar->text();
 m_pRendezVous->m_Type     = comboBox_RdvType->currentText();
}

//----------------------------------------- pushButton_IdentErase_clicked -----------------------------------------
void Dlg_RDV_Manager::pushButton_IdentErase_clicked()
{lineEdit_Nom->setText( "" );
 lineEdit_Premom->setText( "" );
 textLabel_NumGUID->setText( "" );
 lineEdit_Motif->setText( "" );
 //lineEdit_RdvPrisPar->setText( "" );
 lineEdit_Tel->setText( "" );
 DialogToRendezVous(1);
}

//----------------------------------------- pushButton_OK_clicked -----------------------------------------
void Dlg_RDV_Manager::pushButton_OK_clicked()
{DialogToRendezVous(1);
 if (VerifyDate()) accept();
}


//----------------------------------------- pushButton_Annuler_clicked -----------------------------------------
void Dlg_RDV_Manager::pushButton_Annuler_clicked()
{disconnect( lineEdit_Heure, SIGNAL( Sig_FocusOut( )),
                               0,               0 );
 disconnect( lineEdit_Duree, SIGNAL( Sig_FocusOut( )),
                               0,               0 );
 reject();
}


//--------------------------------- DoPopupList ----------------------------------------------------------------------
QString Dlg_RDV_Manager::DoPopupList(QStringList &list)
{m_CurrentPopupItem = "";
 m_RetPopupItem     = "";
 if (m_pQPopupMenu)          return m_RetPopupItem;
 m_pQPopupMenu      =        new QPopupMenu(0, "MyPopupMenu" );
 if (m_pQPopupMenu==0)       return m_RetPopupItem;
 //.......................... creer les items de menu .....................
 if (list.count()>1)  // si 1 seul intervale c'est qu'il n'y a pas de rendez-vous
    {for ( QStringList::Iterator it =list.begin(); it != list.end(); ++it )
         {m_pQPopupMenu->insertItem( *(it),    this, SLOT( GetPopupItem()),  0 );
         }
    }
 else
    {m_pQPopupMenu->insertItem( tr("Tout est libre pour ce jour"),    this, SLOT( GetPopupItem()),  0 );
    }
 //................. connecter le menu .................................................................
 connect( m_pQPopupMenu, SIGNAL( activated( int)),
          this,          SLOT(OnMenuActivated( int))
        );

 if (m_pQPopupMenu->exec( QCursor::pos() /* mapToGlobal (  QPoint ( x, y) )*/ )== -1) m_RetPopupItem ="";
 delete  m_pQPopupMenu;
 m_pQPopupMenu = 0;
 return  m_RetPopupItem;
}

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

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





