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

#include "Trace.h"
#include "Thread.h"
#include "CoreApplication.h"

namespace QGpCoreTools {

#ifdef TRACE_ENABLED

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

  To get a debug trace of all functions, you can define in an implementation files (.cpp):
  \pre
    #ifdef TRACE
    #  undef TRACE
    #endif
    #define TRACE printf("%s\n",__PRETTY_FUNCTION__);
  \pre
*/

QStack<const TraceStamp *> Trace::_mainStack;

/*!
  Description of constructor still missing
*/
Trace::Trace(const TraceStamp * s)
{
  QThread * t=QThread::currentThread();
  Thread * myt=qobject_cast<Thread *>(t);
  if(myt) {
    _myStack=myt->stack();
    _myStack->push(s);
  } else if(t==CoreApplication::instance()->mainThread()) {
    _myStack=&_mainStack;
    _myStack->push(s);
  } else {
    _myStack=0;
  }
  //printf("[TRACE] %s\n",s->toString().toLatin1().data());
  //fflush(stdout);
}

/*!
  Description of destructor still missing
*/
Trace::~Trace()
{
  if(_myStack) {
    _myStack->pop();
  }
}

QString Trace::backTrace(const QStack<const TraceStamp *> * stack)
{
  QString list;
  for(int i=stack->count()-1;i>=0;i--) {
    list += stack->at(i)->toString();
    list += "\n";
  }
  return list;
}

#endif

} // namespace QGpCoreTools
