/***************************************************************************
**
**  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: 2007-07-10
**  Copyright: 2007-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include <time.h>

#include "ConsoleProgress.h"
#include "Global.h"
#include "ApplicationHelp.h"
#include "CoreApplication.h"
#include "MemoryChecker.h"

namespace QGpCoreTools {

/*!
  \class ConsoleProgress ConsoleProgress.h
  \brief Brief description of class still missing

  Full description of class still missing
*/

void ConsoleProgress::setCaption(QString c)
{
  TRACE;
  QString line;
  line=ApplicationHelp::getLine(c, CoreApplication::instance()->terminalCols());
  while(c.length()>0) {
    fprintf(stderr,"%s\n", line.toLatin1().data());
    line=ApplicationHelp::getLine(c, CoreApplication::instance()->terminalCols());
  }
  QMutexLocker ml(&_mutex);
  _caption=line;
  static const QString fmt("%1: --");
  QString msg=fmt.arg(_caption);
  fprintf(stderr,"%s\n", msg.toLatin1().data());
}

void ConsoleProgress::paint(QString caption, int value, int maximum)
{
  static const QString fmt("%1: %2");
  QString msg=fmt.arg(caption).arg(valueString(value, maximum));
  msg=msg.leftJustified(CoreApplication::instance()->terminalCols()-1);
  fprintf(stderr,"%c[1A%s\n", 0x1B, msg.toLatin1().data());
#ifdef Q_OS_WIN
  fflush(stderr);
#endif
}

void ConsoleProgress::end(int val)
{
  TRACE;
  QString msg;
  QMutexLocker ml(&_mutex);
  if(val>_maximum) {
    msg=QString("%1: %2").arg(_caption).arg(val);
  } else {
    msg=QString("%1: 100 %").arg(_caption);
  }
  msg=msg.leftJustified(CoreApplication::instance()->terminalCols()-1);
  fprintf(stderr,"%c[1A%s\n", 0x1B, msg.toLatin1().data());
}

} // namespace QGpCoreTools
