
// File: test_timsdata_reader_memory.cpp
// Created by: Olivier Langella
// Created on: 12/2/2021
//
/*******************************************************************************
 * Copyright (c) 2021 Olivier Langella
 *<olivier.langella@universite-paris-saclay.fr>.
 *
 * This file is part of the PAPPSOms++ library.
 *
 *     PAPPSOms++ 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++ 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++.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

// make test ARGS="-V -I 1,1"

// ./tests/catch2-only-tests [MemTimsData] -s
// ./tests/catch2-only-tests [MonothreadTimsData] -s
// ./tests/catch2-only-tests [rusconi] -s


#include <catch2/catch_test_macros.hpp>


#include <QDebug>
#include <QThreadPool>

#include <pappsomspp/core/msfile/msfileaccessor.h>
#include <pappsomspp/core/msrun/output/mzxmloutput.h>
#include <pappsomspp/core/processing/tandemwrapper/tandemwrapperrun.h>
#include <pappsomspp/core/processing/uimonitor/uimonitorvoid.h>
#include <pappsomspp/core/processing/uimonitor/uimonitortext.h>
#include <pappsomspp/core/msrun/private/timsmsrunreaderms2.h>
#include "tests/tests-config.h"


using namespace pappso;

TEST_CASE("Check memory usage of tandemrun wrapper.", "[MemTandemWrapper]")
{
  qSetMessagePattern(QString("%{file}@%{line}, %{function}(): %{message}"));
#if USEPAPPSOTREE == 1


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

  TandemWrapperRun run_tandem("/usr/bin/tandem", "/tmp");
  UiMonitorText monitor(outputStream);
  for(int i = 0; i < 5; i++)
    {
      INFO(QString("run %1").arg(i).toStdString());
      run_tandem.run(monitor,
                     QString("%1/tests/data/tandem/tandem_run_params.xml")
                       .arg(CMAKE_SOURCE_DIR));
    }
#elif USEPAPPSOTREE == 1

  std::cout << std::endl << "..:: NO test TIMS TDF parsing ::.." << std::endl;

#endif
}

TEST_CASE("Check memory usage of timsdata reader.", "[MemTimsData]")
{
  // VIRT 484Mo => 666Mo scan num="23944"
  qSetMessagePattern(QString("%{file}@%{line}, %{function}(): %{message}"));
#if USEPAPPSOTREE == 1
  INFO("Test case start");

  /*
  pappso::MsFileAccessor file_access_A01(
    //     "/gorgone/pappso/data_extraction_pappso/mzXML/"
    "/gorgone/pappso/versions_logiciels_pappso/masschroq/donnees/"
    "PXD014777_maxquant_timstof/"
    "20180809_120min_200ms_WEHI25_brute20k_timsON_100ng_HYE124A_Slot1-7_1_890."
    "d",
    "");
*/

  pappso::MsFileAccessor file_access_A01(
    //     "/gorgone/pappso/data_extraction_pappso/mzXML/"
    "/gorgone/pappso/fichiers_fabricants/Bruker/tims_doc/tdf-sdk/example_data/"
    "200ngHeLaPASEF_2min_compressed.d",
    "");

  /*
  pappso::MsFileAccessor file_access_A01(
    //     "/gorgone/pappso/data_extraction_pappso/mzXML/"
    "/home/langella/data1/bruker/5-18-2021_1_robert_28_mic02-std_1354.d",
    "");
*/
  INFO(QString("number of runIds = %1")
         .arg(file_access_A01.getMsRunIds().size())
         .toStdString());
  pappso::MsRunReaderSPtr msrunA01 =
    file_access_A01.getMsRunReaderSPtrByRunId("", "runa01");
  file_access_A01.setPreferredFileReaderType(Enums::MsDataFormat::brukerTims,
                                             Enums::FileReaderType::tims_ms2);
  file_access_A01.getMsRunIds();

  QTextStream outputStream(stdout, QIODevice::WriteOnly);
  UiMonitorText monitor(outputStream);


  pappso::MsRunReaderSPtr p_reader;
  p_reader =
    file_access_A01.msRunReaderSPtr(file_access_A01.getMsRunIds().front());

  pappso::TimsMsRunReaderMs2 *tims2_reader =
    dynamic_cast<pappso::TimsMsRunReaderMs2 *>(p_reader.get());
  REQUIRE(tims2_reader != nullptr);
  if(tims2_reader != nullptr)
    {
      qDebug();
      tims2_reader->setMs2BuiltinCentroid(true);

      std::shared_ptr<pappso::FilterSuiteString> ms2filter;
      QString filters_str =
        "chargeDeconvolution|0.02dalton mzExclusion|0.01dalton";
      ms2filter = std::make_shared<pappso::FilterSuiteString>(filters_str);

      monitor.setStatus(QString("timsTOF MS2 filters : %1").arg(filters_str));

      tims2_reader->setMs2FilterCstSPtr(ms2filter);

      qDebug();
    }


  // 517760
  // REQUIRE(p_reader.get()->spectrumListSize() == 517760);


  QFile output_file("/tmp/test.xml");
  // qDebug() << " TsvDirectoryWriter::writeSheet " <<
  // QFileInfo(*_p_ofile).absoluteFilePath();
  REQUIRE(output_file.open(QIODevice::WriteOnly));
  pappso::UiMonitorVoid monitor_null;

  pappso::MzxmlOutput mzxml_ouput(monitor_null,
                                  QTextStream(&output_file).device());

  mzxml_ouput.setReadAhead(true);
  mzxml_ouput.maskMs1(true);
  QThreadPool::globalInstance()->setMaxThreadCount(10);
  mzxml_ouput.write(p_reader.get());

  mzxml_ouput.close();
#elif USEPAPPSOTREE == 1

  std::cout << std::endl << "..:: NO test TIMS TDF parsing ::.." << std::endl;

#endif
}


TEST_CASE("Check monothread usage of timsdata reader.", "[MonothreadTimsData]")
{
  // VIRT 484Mo => 666Mo scan num="23944"
  qSetMessagePattern(QString("%{file}@%{line}, %{function}(): %{message}"));
#if USEPAPPSOTREE == 1
  INFO("Test case start");

  /*
  pappso::MsFileAccessor file_access_A01(
    //     "/gorgone/pappso/data_extraction_pappso/mzXML/"
    "/gorgone/pappso/versions_logiciels_pappso/masschroq/donnees/"
    "PXD014777_maxquant_timstof/"
    "20180809_120min_200ms_WEHI25_brute20k_timsON_100ng_HYE124A_Slot1-7_1_890."
    "d",
    "");
*/

  pappso::MsFileAccessor file_access_A01(
    //     "/gorgone/pappso/data_extraction_pappso/mzXML/"
    "/gorgone/pappso/fichiers_fabricants/Bruker/tims_doc/tdf-sdk/example_data/"
    "200ngHeLaPASEF_2min_compressed.d",
    "");

  /*
  pappso::MsFileAccessor file_access_A01(
    //     "/gorgone/pappso/data_extraction_pappso/mzXML/"
    "/home/langella/data1/bruker/5-18-2021_1_robert_28_mic02-std_1354.d",
    "");
*/
  INFO(QString("number of runIds = %1")
         .arg(file_access_A01.getMsRunIds().size())
         .toStdString());
  pappso::MsRunReaderSPtr msrunA01 =
    file_access_A01.getMsRunReaderSPtrByRunId("", "runa01");
  file_access_A01.setPreferredFileReaderType(Enums::MsDataFormat::brukerTims,
                                             Enums::FileReaderType::tims_ms2);
  file_access_A01.getMsRunIds();

  QTextStream outputStream(stdout, QIODevice::WriteOnly);
  UiMonitorText monitor(outputStream);


  pappso::MsRunReaderSPtr p_reader;
  p_reader =
    file_access_A01.msRunReaderSPtr(file_access_A01.getMsRunIds().front());

  pappso::TimsMsRunReaderMs2 *tims2_reader =
    dynamic_cast<pappso::TimsMsRunReaderMs2 *>(p_reader.get());
  REQUIRE(tims2_reader != nullptr);
  if(tims2_reader != nullptr)
    {
      qDebug();
      tims2_reader->setMs2BuiltinCentroid(true);

      std::shared_ptr<pappso::FilterSuiteString> ms2filter;
      QString filters_str =
        "chargeDeconvolution|0.02dalton mzExclusion|0.01dalton";
      ms2filter = std::make_shared<pappso::FilterSuiteString>(filters_str);

      monitor.setStatus(QString("timsTOF MS2 filters : %1").arg(filters_str));

      tims2_reader->setMs2FilterCstSPtr(ms2filter);

      qDebug();
    }


  // 517760
  // REQUIRE(p_reader.get()->spectrumListSize() == 517760);
  p_reader.get()->setMonoThread(true);

  QFile output_file("/tmp/test.xml");
  // qDebug() << " TsvDirectoryWriter::writeSheet " <<
  // QFileInfo(*_p_ofile).absoluteFilePath();
  REQUIRE(output_file.open(QIODevice::WriteOnly));
  pappso::UiMonitorVoid monitor_null;

  pappso::MzxmlOutput mzxml_ouput(monitor_null,
                                  QTextStream(&output_file).device());

  mzxml_ouput.setReadAhead(true);
  mzxml_ouput.maskMs1(true);
  QThreadPool::globalInstance()->setMaxThreadCount(10);
  mzxml_ouput.write(p_reader.get());

  mzxml_ouput.close();
#elif USEPAPPSOTREE == 1

  std::cout << std::endl << "..:: NO test TIMS TDF parsing ::.." << std::endl;

#endif
}


TEST_CASE("Check speed of timsdata reader.", "[rusconi]")
{
  // VIRT 484Mo => 666Mo scan num="23944"
  qSetMessagePattern(QString("%{file}@%{line}, %{function}(): %{message}"));
#if USEPAPPSOTREE == 1
  INFO("Test case start");

  /*
  pappso::MsFileAccessor file_access_A01(
    //     "/gorgone/pappso/data_extraction_pappso/mzXML/"
    "/gorgone/pappso/versions_logiciels_pappso/masschroq/donnees/"
    "PXD014777_maxquant_timstof/"
    "20180809_120min_200ms_WEHI25_brute20k_timsON_100ng_HYE124A_Slot1-7_1_890."
    "d",
    "");
*/

  pappso::MsFileAccessor file_access_A01(
    //     "/gorgone/pappso/data_extraction_pappso/mzXML/"
    "/gorgone/pappso/fichiers_fabricants/Bruker/tims_doc/tdf-sdk/example_data/"
    "200ngHeLaPASEF_2min_compressed.d",
    "");

  /*
  pappso::MsFileAccessor file_access_A01(
    //     "/gorgone/pappso/data_extraction_pappso/mzXML/"
    "/home/langella/data1/bruker/5-18-2021_1_robert_28_mic02-std_1354.d",
    "");
*/
  INFO(QString("number of runIds = %1")
         .arg(file_access_A01.getMsRunIds().size())
         .toStdString());

  QTextStream outputStream(stdout, QIODevice::WriteOnly);
  UiMonitorText monitor(outputStream);


  pappso::MsRunReaderSPtr p_reader;
  p_reader =
    file_access_A01.msRunReaderSPtr(file_access_A01.getMsRunIds().front());


  Trace tic = p_reader.get()->getTicChromatogram();

  qWarning() << tic.toString();
  INFO(tic.toString().toStdString());
/*
  // 517760
  // REQUIRE(p_reader.get()->spectrumListSize() == 517760);
  class Translator : public SpectrumCollectionHandlerInterface
  {
    public:
    Translator(){};
    virtual ~Translator(){};
    virtual void
    setQualifiedMassSpectrum(const QualifiedMassSpectrum &spectrum) override
    {
      qDebug() << spectrum.toString();
    };
    virtual bool
    needPeakList() const override
    {
      return true;
    };

    private:
  };

  Translator reader_handler;

  reader_handler.setNeedMsLevelPeakList(1, true);
  reader_handler.setNeedMsLevelPeakList(2, true);
  // reader_handler.setNeedMsLevelPeakList(2,false);

  p_reader.get()->readSpectrumCollectionByMsLevel(reader_handler, 1);
  // p_reader.get()->readSpectrumCollection(reader_handler);

  QFile output_file("/dev/null");
  // qDebug() << " TsvDirectoryWriter::writeSheet " <<
  // QFileInfo(*_p_ofile).absoluteFilePath();
  REQUIRE(output_file.open(QIODevice::WriteOnly));
  pappso::UiMonitorVoid monitor_null;

  pappso::MzxmlOutput mzxml_ouput(monitor_null,
                                  QTextStream(&output_file).device());

  mzxml_ouput.setReadAhead(true);
  // mzxml_ouput.maskMs1(true);
  QThreadPool::globalInstance()->setMaxThreadCount(10);
  mzxml_ouput.write(p_reader.get());

  mzxml_ouput.close();
  */
#elif USEPAPPSOTREE == 1

  std::cout << std::endl << "..:: NO test TIMS TDF parsing ::.." << std::endl;

#endif
}
