/***************************************************************************
**
**  This file is part of waran.
**
**  waran 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.
**
**  waran 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: 2012-02-08
**  Copyright: 2012-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#include "DownloadGpsRaw.h"
#include "Station.h"

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

  Full description of class still missing
*/

/*!
  Description of constructor still missing
*/
DownloadGpsRaw::DownloadGpsRaw(QWidget * parent)
  : Dialog(parent)
{
  TRACE;
  setupUi(this);
}

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

void DownloadGpsRaw::addStation(Station * s)
{
  TRACE;
  int i=_stations.count();
  _stations.insert(s, i);
  stations->setRowCount(i+1);
  stations->setItem(i, 0, new QTableWidgetItem(s->name()));
  stations->setItem(i, 1, new QTableWidgetItem("waiting"));
  stations->setItem(i, 2, new QTableWidgetItem("0"));
  connect(s, SIGNAL(rawFileReady()), this, SLOT(rawFileReady()));
  connect(s, SIGNAL(rawFileError()), this, SLOT(rawFileError()));
  connect(s, SIGNAL(rawFileSize(int)), this, SLOT(rawFileSize(int)));
}

void DownloadGpsRaw::terminate()
{
  TRACE;
  for(QMap<Station *, int>::iterator it=_stations.begin(); it!=_stations.end(); it++) {
    it.key()->abortDownloadGps();
  }
}

void DownloadGpsRaw::toRinex()
{
  TRACE;
  MessageContext mc;
  for(QMap<Station *, int>::iterator it=_stations.begin(); it!=_stations.end(); it++) {
    if(stations->item(it.value(), 1)->text()=="finished") {
      Station * s=it.key();
      QString gpsName=s->name();
      gpsName.replace("WAU", "WA");
      QProcess p;
      p.setProcessChannelMode(QProcess::MergedChannels);
      QString cmd("teqc -ublox ubx -O.mo ");
      cmd+=gpsName;
      cmd+=" -O.rn ";
      cmd+=gpsName;
      cmd+=" -O.int 1 +nav ";
      cmd+=s->currentGpsFileName()+"n";
      cmd+=" +obs ";
      cmd+=s->currentGpsFileName()+"o";
      cmd+=" ";
      cmd+=s->currentGpsFileName()+"ubx";
      App::log(cmd+"\n");
      p.start(cmd);
      p.waitForFinished(100); // wait 60 s
      p.waitForFinished(60000); // wait 60 s
      if(p.state()==QProcess::Running) {
        p.kill();
        Message::warning(MSG_ID, tr("Rinex conversion"), tr("Time out running teqc for station '%1'").arg(s->name()), Message::ok(), true);
      } else {
        switch(p.exitStatus()) {
        case QProcess::NormalExit:
          switch(p.exitCode()) {
          case 0:
            break;
          default:
            Message::warning(MSG_ID, tr("Rinex conversion"),
                             tr("teqc returned code %1 for station '%2'").arg(p.exitCode()).arg(s->name()),
                             Message::ok(), true);
            break;
          }
          break;
        default:
          Message::warning(MSG_ID, tr("Rinex conversion"),
                           tr("teqc crashed for station '%1'").arg(s->name()),
                           Message::ok(), true);
          break;
        }
      }
    }
  }
  Message::information(MSG_ID, tr("Rinex conversion"),
                       tr("All ubx file are now converted to Rinex in /tmp/waran. You can post-process them."),
                       Message::ok());
}

void DownloadGpsRaw::rawFileSize(int size)
{
  TRACE;
  Station * s=qobject_cast<Station *>(sender());
  QMap<Station *, int>::iterator it=_stations.find(s);
  if(it!=_stations.end()) {
    stations->item(it.value(), 1)->setText("download");
    stations->item(it.value(), 2)->setText(QString::number(size));
  }
}

void DownloadGpsRaw::rawFileReady()
{
  TRACE;
  Station * s=qobject_cast<Station *>(sender());
  QMap<Station *, int>::iterator it=_stations.find(s);
  if(it!=_stations.end()) {
    stations->item(it.value(), 1)->setText("finished");
  }
}

void DownloadGpsRaw::rawFileError()
{
  TRACE;
  Station * s=qobject_cast<Station *>(sender());
  QMap<Station *, int>::iterator it=_stations.find(s);
  if(it!=_stations.end()) {
    stations->item(it.value(), 1)->setText("error");
  }
}
