/***************************************************************************
**
**  This file is part of QGpCoreTools.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file 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 Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2004-10-28
**  Copyright: 2004-2019
**    Marc Wathelet
**    Marc Wathelet (ULg, Liège, Belgium)
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include "ThreadTimer.h"
#include "Trace.h"

namespace QGpCoreTools {

ThreadTimer::ThreadTimer()
{
  TRACE;
  _nofRunningThreads=0;
  connect((QTimer*)this,SIGNAL(timeout()),this,SLOT(synchronize()));
  setSingleShot(true);
}

void ThreadTimer::threadStarted()
{
  TRACE;
  if(_nofRunningThreads==0) {
    start(200);
  }
  _nofRunningThreads++;
}

void ThreadTimer::threadStopped()
{
  TRACE;
  _nofRunningThreads--;
  if(_nofRunningThreads<=0) {
    stop();
    QTimer::singleShot(500, this, SIGNAL(synchroTimeout()));
  }
}

void ThreadTimer::synchronize()
{
  TRACE;
  QElapsedTimer chrono;
  chrono.start();
  emit synchroTimeout();
  QCoreApplication::processEvents();
  int updateDelay=5*chrono.elapsed();
  if(updateDelay<1000) updateDelay=1000;
  start(updateDelay);
}

} // namespace QGpCoreTools
