/***************************************************************************
**
**  This file is part of GeopsyCore.
**
**  GeopsyCore is free software: you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation, either version 3 of the License, or
**  (at your option) any later version.
**
**  GeopsyCore 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 General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with Foobar.  If not, see <http://www.gnu.org/licenses/>
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2010-03-22
**  Copyright: 2010-2019
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include "AsciiSignalFormatReader.h"

namespace GeopsyCore {

/*!
  \class AsciiSignalFormatReader AsciiSignalFormatReader.h
  \brief Threaded parser for reading ASCII signal formats

  This class is used mainly for viewing an ASCII file while editing the parser parameters.
*/

/*!
  Description of constructor still missing
*/
AsciiSignalFormatReader::AsciiSignalFormatReader(QObject * parent)
    : Thread(parent)
{
  TRACE;
  setObjectName("AsciiSignalFormatReader");
}

/*!
  Description of destructor still missing
*/
AsciiSignalFormatReader::~AsciiSignalFormatReader()
{
  TRACE;
  stop();
}  

void AsciiSignalFormatReader::setFileName(const QString& f)
{
  TRACE;
  stop();
  _fileName=f;
  _stopRequest=false;
  start();
}

void AsciiSignalFormatReader::setFormat(const AsciiSignalFormat& f)
{
  TRACE;
  stop();
  _format=f;
  _stopRequest=false;
  start();
}

void AsciiSignalFormatReader::stop()
{
  TRACE;
  if(isRunning()) {
    _stopRequest.fetchAndStoreOrdered(true);
    wait();
  }
}

void AsciiSignalFormatReader::run()
{
  TRACE;
  _header.clear();
  if(!_fileName.isEmpty()) {
    QFile f(_fileName);
    if(f.open(QIODevice::ReadOnly)) {
      QTextStream s(&f);
      int lineNumber=0;
      _header=_format.header(s, lineNumber, &_stopRequest);
      if(_stopRequest.testAndSetOrdered(true,true)) {
        App::log(tr("User interrupt while defining header\n") );
        emit dataChanged();
        return;
      }
      _format.parseHeader(_header, &_stopRequest);
      if(_stopRequest.testAndSetOrdered(true,true)) {
        App::log(tr("User interrupt while parsing header\n") );
      }
    } else {
      App::log(tr("Unable to open file %1\n").arg(_fileName) );
    }
  } else {
    App::log(tr("Provide a file name for testing your parser\n") );
  }
  emit dataChanged();
}

} // namespace GeopsyCore
