/***************************************************************************
**
**  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: 2008-02-20
**  Copyright: 2008-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#ifndef ABSTRACTPROGRESS_H
#define ABSTRACTPROGRESS_H

#include <time.h>

#include "QGpCoreToolsDLLExport.h"
#include "Mutex.h"
#include "Trace.h"

namespace QGpCoreTools {

class QGPCORETOOLS_EXPORT AbstractProgress
{
public:
  AbstractProgress();
  virtual ~AbstractProgress() {}

  virtual void setMaximum(int val);
  int maximum() const;

  virtual void setCaption(QString c);
  const QString& caption() const;

  inline void setValue(int val);
  inline void increaseValue(int val=1);
  int value() const {return _value+_deltaValue;}
protected:
  virtual void paint(QString caption, int value, int maximum)=0;
  QString valueString(int value, int maximum);

  mutable Mutex _mutex;
  QString _caption;
  int _value;
  int _maximum;
private:
  void setValueInternal(int val);
  void increaseValueInternal();

  QAtomicInteger<qint64> _lastTime;
  int _deltaValue;
};

inline void AbstractProgress::increaseValue(int val)
{
  TRACE;
  _deltaValue+=val; // Several increments may stack up if they arrive too fast.
  qint64 now=time(nullptr);
  if(_lastTime.fetchAndStoreOrdered(now)!=now) {
    increaseValueInternal();
    _deltaValue=0;
  }
}

inline void AbstractProgress::setValue(int val)
{
  TRACE;
  qint64 now=time(nullptr);
  if(_lastTime.fetchAndStoreOrdered(now)!=now || val==_maximum) {
    setValueInternal(val);
  }
}

} // namespace QGpCoreTools

#endif // ABSTRACTPROGRESS_H
