/**
 * \file tandemwrapper.cpp
 * \date 25/01/2020
 * \author Olivier Langella
 * \brief run tandem directly on Bruker's data
 */

/*******************************************************************************
 * Copyright (c) 2020 Olivier Langella <Olivier.Langella@u-psud.fr>.
 *
 * This file is part of PAPPSOms-tools.
 *
 *     PAPPSOms-tools 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.
 *
 *     PAPPSOms-tools 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 PAPPSOms-tools.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

#include "tandemwrapper.h"
#include <QCommandLineParser>
#include <QDateTime>
#include <QTimer>
#include <QFile>
#include <pappsomspp/pappsoexception.h>
#include <pappsomspp/processing/tandemwrapper/tandemwrapperrun.h>
#include <pappsomspp/processing/uimonitor/uimonitortext.h>

TandemWrapper::TandemWrapper(QObject *parent) : QObject(parent)
{
  // get the instance of the main application
  app = QCoreApplication::instance();
  // setup everything here
  // create any global objects
  // setup debug and warning mode
}

// 10ms after the application starts this method will run
// all QT messaging is running at this point so threads, signals and slots
// will all work as expected.
void
TandemWrapper::run()
{
  qSetMessagePattern(QString("%{file}@%{line}, %{function}(): %{message}"));
  /* ./src/pt-mzxmlconverter -i
   /gorgone/pappso/fichiers_fabricants/Bruker/tims_doc/tdf-sdk/example_data/200ngHeLaPASEF_2min_compressed.d/analysis.tdf
   -o
   /gorgone/pappso/versions_logiciels_pappso/xtpcpp/bruker/200ngHeLaPASEF_2min.mzXML
  */

  //./src/pt-mzxmlconverter -i
  /// gorgone/pappso/fichiers_fabricants/Bruker/tims_doc/tdf-sdk/example_data/200ngHeLaPASEF_2min_compressed.d/analysis.tdf
  //-o /tmp/test.xml


  QTextStream errorStream(stderr, QIODevice::WriteOnly);
  QTextStream outputStream(stdout, QIODevice::WriteOnly);

  try
    {
      qDebug();
      QCommandLineParser parser;

      // throw pappso::PappsoException("test");
      parser.setApplicationDescription(
        QString("%1 ")
          .arg(QCoreApplication::applicationName())
          .append("tandemwrapper")
          .append(" ")
          .append(XTPCPP_VERSION)
          .append(" tandem run on Bruker's data"));
      parser.addHelpOption();
      parser.addVersionOption();
      QCommandLineOption tandemOption(
        QStringList() << "tandem",
        QCoreApplication::translate("tandem",
                                    "tandem executable binary file <tandem>."),
        QCoreApplication::translate("tandem", "tandem"));


      QCommandLineOption tmpDirOption(
        QStringList() << "t"
                      << "tmp",
        QCoreApplication::translate("tmp", "temporary directory"),
        QCoreApplication::translate("tmp", "tmp"));


      parser.addOption(tandemOption);
      parser.addOption(tmpDirOption);

      qDebug();

      // Process the actual command line arguments given by the user
      parser.process(*app);

      // QCoreApplication * app(this);
      // Add your main code here
      qDebug();
      const QDateTime dt_begin = QDateTime::currentDateTime();
      const QStringList args   = parser.positionalArguments();


      pappso::TandemWrapperRun tandem_run(parser.value(tandemOption),
                                          parser.value(tmpDirOption));


      if(args.size() > 0)
        {
          pappso::UiMonitorText monitor(outputStream);
          tandem_run.run(monitor, args[0]);
        }

      qDebug();
    }
  catch(pappso::PappsoException &error)
    {
      errorStream << "Oops! an error occurred in PAPPSO MS tools. Dont Panic :"
                  << Qt::endl;
      errorStream << error.qwhat() << Qt::endl;
      exit(1);
      app->exit(1);
    }

  catch(std::exception &error)
    {
      errorStream << "Oops! an error occurred in PAPPSO MS tools. Dont Panic :"
                  << Qt::endl;
      errorStream << error.what() << Qt::endl;
      exit(1);
      app->exit(1);
    }


  // you must call quit when complete or the program will stay in the
  // messaging loop
  quit();
}

// call this routine to quit the application
void
TandemWrapper::quit()
{
  // you can do some cleanup here
  // then do emit finished to signal CoreApplication to quit
  emit finished();
}

// shortly after quit is called the CoreApplication will signal this routine
// this is a good place to delete any objects that were created in the
// constructor and/or to stop any threads
void
TandemWrapper::aboutToQuitApp()
{
  // stop threads
  // sleep(1);   // wait for threads to stop.
  // delete any objects
}


int
main(int argc, char **argv)
{
  // QTextStream consoleErr(stderr);
  // QTextStream consoleOut(stdout, QIODevice::WriteOnly);
  // ConsoleOut::setCout(new QTextStream(stdout, QIODevice::WriteOnly));
  // ConsoleOut::setCerr(new QTextStream(stderr, QIODevice::WriteOnly));
  qDebug();
  QCoreApplication app(argc, argv);
  qDebug();
  QCoreApplication::setApplicationName("tandemwrapper");
  QCoreApplication::setApplicationVersion(XTPCPP_VERSION);
  QLocale::setDefault(QLocale::system());

  // create the main class
  TandemWrapper myMain;
  // connect up the signals
  QObject::connect(&myMain, SIGNAL(finished()), &app, SLOT(quit()));
  QObject::connect(
    &app, SIGNAL(aboutToQuit()), &myMain, SLOT(aboutToQuitApp()));
  qDebug();


  // This code will start the messaging engine in QT and in
  // 10ms it will start the execution in the MainClass.run routine;
  QTimer::singleShot(10, &myMain, SLOT(run()));
  return app.exec();
}
