
/*******************************************************************************
 * Copyright (c) 2023 Olivier Langella <Olivier.Langella@u-psud.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/>.
 *
 ******************************************************************************/

// cmake .. -DCMAKE_BUILD_TYPE=Debug  -DMAKE_TESTS=1  -DUSEPAPPSOTREE=1

//./tests/pappsotree/catch2-only-pappsotree [MsRunReader] -s
//./tests/pappsotree/catch2-only-pappsotree [MsRunReaderPerf] -s
//./tests/pappsotree/catch2-only-pappsotree [MsRunReaderPerf] -s
//--benchmark-samples 5


#include <catch2/catch_test_macros.hpp>
#include <catch2/catch_approx.hpp>
#include <catch2/matchers/catch_matchers_vector.hpp>


#include <iostream>

#include <pappsomspp/core/pappsoexception.h>
#include <pappsomspp/core/exception/exceptionnotpossible.h>
#include <pappsomspp/core/msfile/msfileaccessor.h>
#include <pappsomspp/core/msrun/output/mzxmloutput.h>
#include <pappsomspp/core/processing/uimonitor/uimonitorvoid.h>
#include <pappsomspp/core/msrun/private/timsframesmsrunreader.h>
#include <pappsomspp/core/msrun/private/timsmsrunreader.h>
#include <pappsomspp/core/processing/filters/filterpass.h>
#include <QDebug>
#include <QtCore>
#include <QFile>
#include <QtConcurrent>
#include "config.h"
#include <pappsomspp/core/msrun/msrunreadconfig.h>

// #include "common.h"

using namespace std;


TEST_CASE("Test MsRunReader new API", "[MsRunReader]")
{

  // Set the debugging message formatting pattern.
  qSetMessagePattern(QString("%{file}@%{line}, %{function}(): %{message}"));

  SECTION("..::  test that with or without analysis.tdf, sample name is OK ::..")

  {
    pappso::MsFileAccessor file_access_bruker_analysis(
      "/gorgone/pappso/versions_logiciels_pappso/bruker/"
      "200ngHeLaPASEF_2min_compressed.d/analysis.tdf",
      "");
    file_access_bruker_analysis.setPreferredFileReaderType(
      pappso::Enums::MsDataFormat::brukerTims, pappso::Enums::FileReaderType::tims_frames);
    pappso::MsRunReaderSPtr msrunA01 =
      file_access_bruker_analysis.getMsRunReaderSPtrByRunId("", "runa01");

    REQUIRE(msrunA01.get()->getMsRunId().get()->getSampleName().toStdString() ==
            "200ngHeLaPASEF_2min_compressed");

    pappso::MsFileAccessor file_access_bruker(
      "/gorgone/pappso/versions_logiciels_pappso/bruker/"
      "200ngHeLaPASEF_2min_compressed.d",
      "");
    file_access_bruker.setPreferredFileReaderType(pappso::Enums::MsDataFormat::brukerTims,
                                                  pappso::Enums::FileReaderType::tims_frames);
    pappso::MsRunReaderSPtr msrun_new = file_access_bruker.getMsRunReaderSPtrByRunId("", "runa01");

    REQUIRE(msrun_new.get()->getMsRunId().get()->getSampleName().toStdString() ==
            "200ngHeLaPASEF_2min_compressed");

    REQUIRE(msrun_new.get()->getMsRunId().get()->getSampleName().toStdString() ==
            msrunA01.get()->getMsRunId().get()->getSampleName().toStdString());

    REQUIRE(msrun_new.get()->getMsRunId().get()->getFileName().toStdString() ==
            msrunA01.get()->getMsRunId().get()->getFileName().toStdString());
  }

  SECTION("..::  test mz merge on tims_frames ::..")

  {
    pappso::MsFileAccessor file_access_bruker(
      "/gorgone/pappso/versions_logiciels_pappso/bruker/"
      "200ngHeLaPASEF_2min_compressed.d/analysis.tdf",
      "");
    file_access_bruker.setPreferredFileReaderType(pappso::Enums::MsDataFormat::brukerTims,
                                                  pappso::Enums::FileReaderType::tims_frames);
    pappso::MsRunReaderSPtr msrunA01 = file_access_bruker.getMsRunReaderSPtrByRunId("", "runa01");

    REQUIRE(msrunA01.get()->getMsRunId().get()->getSampleName().toStdString() ==
            "200ngHeLaPASEF_2min_compressed");
    pappso::TimsFramesMsRunReader *p_msreader_tims =
      dynamic_cast<pappso::TimsFramesMsRunReader *>(msrunA01.get());

    qDebug();
    REQUIRE(p_msreader_tims->getTimsDataSPtr().get() != nullptr);
    REQUIRE(p_msreader_tims->getTimsDataSPtr().get()->isDdaRun() == true);

    REQUIRE(p_msreader_tims->getTimsDataSPtr().get()->isDiaRun() == false);

    qDebug();
    pappso::MsRunQualifiedSpectrumLoader spectrum_list_reader;

    pappso::MsRunReadConfig config;
    config.setNeedPeakList(true);
    config.setMsLevels({1});
    msrunA01.get()->readSpectrumCollection2(config, spectrum_list_reader);
    REQUIRE(spectrum_list_reader.getQualifiedMassSpectrumList().size() == 131);
    auto spectrum  = spectrum_list_reader.getQualifiedMassSpectrumList().at(100);
    auto peak_list = pappso::FilterGreatestY(10).filter(*(spectrum.getMassSpectrumSPtr().get()));


    std::vector<double> expected_mass_list({706.3999766729,
                                            706.9020200197,
                                            706.9062396402,
                                            707.4042417417,
                                            714.3395398357,
                                            714.3437815601,
                                            715.3494308409,
                                            929.5019128764,
                                            1045.4947003008,
                                            1045.9976567258});
    // REQUIRE(p_msreader_tims->getTimsDataSPtr().get()->isDiaRun() == true);
    REQUIRE_THAT(peak_list.xValues(), Catch::Matchers::Approx(expected_mass_list));

    config.setParameterValue(pappso::MsRunReadConfigParameter::TimsFrameMzIndexMergeWindow, 15);
    spectrum_list_reader.clear();
    msrunA01.get()->readSpectrumCollection2(config, spectrum_list_reader);
    REQUIRE(spectrum_list_reader.getQualifiedMassSpectrumList().size() == 131);

    auto peak_list_merged = pappso::FilterGreatestY(10).filter(
      *(spectrum_list_reader.getQualifiedMassSpectrumList().at(100).getMassSpectrumSPtr().get()));

    std::vector<double> expected_mass_list_merged({575.3077201826,
                                                   679.3848524324,
                                                   706.3915404671,
                                                   706.8978004475,
                                                   707.4042417417,
                                                   714.3225729564,
                                                   715.3409413994,
                                                   929.5261058305,
                                                   1045.5049635122,
                                                   1045.9668599888});
    REQUIRE_THAT(peak_list_merged.xValues(),
                 Catch::Matchers::Approx(expected_mass_list_merged).margin(0.00001));
  }

  SECTION(
    "..::  MsRunReader uses Enums::FileReaderType::tims_frames (explicit reader "
    "config, first on tims_frames"
    "data file) ::..")
  {
    qDebug();
    pappso::MsFileAccessor file_access_A01(
      "/gorgone/pappso/versions_logiciels_pappso/bruker/"
      "200ngHeLaPASEF_2min_compressed.d",
      "");
    std::cout << "number of runIds = " << file_access_A01.getMsRunIds().size() << std::endl;

    file_access_A01.setPreferredFileReaderType(pappso::Enums::MsDataFormat::brukerTims,
                                               pappso::Enums::FileReaderType::tims_frames);
    pappso::MsRunReaderSPtr msrunA01 = file_access_A01.getMsRunReaderSPtrByRunId("", "runa01");

    pappso::MsRunSimpleStatistics simple_stats;

    pappso::MsRunReadConfig config;
    // config.setRetentionTimeStartInSeconds(300);
    // config.setRetentionTimeEndInSeconds(500);
    config.setNeedPeakList(false);
    config.setMsLevels({1, 2});

    REQUIRE(config.getMsLevels()[0] == false);
    REQUIRE(config.getMsLevels()[1] == true);
    REQUIRE(config.getMsLevels()[2] == true);
    REQUIRE(config.getMsLevels()[3] == false);

    REQUIRE(config.acceptRetentionTimeInSeconds(300) == true);
    msrunA01.get()->readSpectrumCollection2(config, simple_stats);

    REQUIRE(simple_stats.getMsLevelCount(1) == 131);

    REQUIRE(config.needPeakList() == false);

    INFO("selecting 0.5s retention time range and only MS level==1");
    // 2499
    config.setMsLevels({1});

    REQUIRE(config.getMsLevels()[0] == false);
    REQUIRE(config.getMsLevels()[1] == true);
    REQUIRE(config.getMsLevels()[2] == false);
    REQUIRE(config.getMsLevels()[3] == false);

    config.setRetentionTimeStartInSeconds(2499);
    config.setRetentionTimeEndInSeconds(2499.5);
    config.setNeedPeakList(true);

    pappso::MsRunQualifiedSpectrumLoader spectrum_list_reader;
    msrunA01.get()->readSpectrumCollection2(config, spectrum_list_reader);

    REQUIRE(spectrum_list_reader.getQualifiedMassSpectrumList().size() == 1);
    REQUIRE(spectrum_list_reader.getQualifiedMassSpectrumList()
              .at(0)
              .getMassSpectrumId()
              .getNativeId()
              .toStdString() ==
            "frame_id=1184 global_scan_index=794464 im_scan_range_begin=0 "
            "im_scan_range_end=670");
    REQUIRE(
      spectrum_list_reader.getQualifiedMassSpectrumList().at(0).getMassSpectrumSPtr()->size() ==
      138397);


    INFO(
      "selecting 0.5s retention time range and only MS level==1, downgrading "
      "mz precision");
    spectrum_list_reader.clear();
    config.setParameterValue(pappso::MsRunReadConfigParameter::TimsFrameMzIndexMergeWindow, 30);

    msrunA01.get()->readSpectrumCollection2(config, spectrum_list_reader);

    REQUIRE(spectrum_list_reader.getQualifiedMassSpectrumList().size() == 1);
    REQUIRE(spectrum_list_reader.getQualifiedMassSpectrumList()
              .at(0)
              .getMassSpectrumId()
              .getNativeId()
              .toStdString() ==
            "frame_id=1184 global_scan_index=794464 im_scan_range_begin=0 "
            "im_scan_range_end=670");
    REQUIRE(
      spectrum_list_reader.getQualifiedMassSpectrumList().at(0).getMassSpectrumSPtr()->size() ==
      10588);

    INFO(
      "selecting 0.5s and only MS level==1, downgrading mz precision and "
      "selecting ion mobility range");
    spectrum_list_reader.clear();
    config.setParameterValue(pappso::MsRunReadConfigParameter::TimsFrameIonMobScanIndexBegin, 150);
    config.setParameterValue(pappso::MsRunReadConfigParameter::TimsFrameIonMobScanIndexEnd, 200);

    msrunA01.get()->readSpectrumCollection2(config, spectrum_list_reader);
    REQUIRE(spectrum_list_reader.getQualifiedMassSpectrumList().size() == 1);
    REQUIRE(spectrum_list_reader.getQualifiedMassSpectrumList()
              .at(0)
              .getMassSpectrumId()
              .getNativeId()
              .toStdString() ==
            "frame_id=1184 global_scan_index=794464 im_scan_range_begin=150 "
            "im_scan_range_end=200");
    REQUIRE(
      spectrum_list_reader.getQualifiedMassSpectrumList().at(0).getMassSpectrumSPtr()->size() ==
      5071);
  }

  SECTION(
    "..::  MsRunReader uses Enums::FileReaderType::tims_frames (explicit reader "
    "config, "
    "second data file) ::..")
  {
    qDebug();
    pappso::MsFileAccessor file_access_A01(
      "/gorgone/pappso/data_extraction_pappso/mzXML/"
      // "/data/mzXML/"
      //"/home/langella/data1/mzxml/"
      "20120906_balliau_extract_1_A01_urnb-1.mzXML",
      "");
    std::cout << "number of runIds = " << file_access_A01.getMsRunIds().size() << std::endl;
    pappso::MsRunReaderSPtr msrunA01 = file_access_A01.getMsRunReaderSPtrByRunId("", "runa01");

    pappso::MsRunReadConfig config;
    config.setRetentionTimeStartInSeconds(300);
    config.setRetentionTimeEndInSeconds(500);
    config.setNeedPeakList(false);
    config.setMsLevels({1, 2});

    pappso::MsRunSimpleStatistics simple_stats;

    msrunA01.get()->readSpectrumCollection2(config, simple_stats);

    REQUIRE(simple_stats.getMsLevelCount(1) == 572);
  }
}
