//
// File: test_timsframe.cpp
// Created by: Olivier Langella
// Created on: 12/4/2020
//
/*******************************************************************************
 * Copyright (c) 2020 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/>.
 *
 ******************************************************************************/

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

// ./tests/catch2-only-tests [timsframe] -s

// ./tests/catch2-only-tests [timsframe] -s -a

#include <catch2/catch.hpp>
#include <QDebug>
#include <QString>
#include <iostream>
#include <pappsomspp/vendors/tims/timsframebase.h>
#include <pappsomspp/mzrange.h>
#include <pappsomspp/msfile/msfileaccessor.h>
#include <pappsomspp/msrun/private/timsmsrunreaderms2.h>
#include <pappsomspp/msrun/private/timsmsrunreader.h>
#include <pappsomspp/pappsoexception.h>
#include <pappsomspp/exception/exceptionnotfound.h>
#include <pappsomspp/processing/filters/filtersuitestring.h>
#include "config.h"

using namespace pappso;
using namespace std;


TEST_CASE("Test tims frames", "[timsframe]")
{

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

  INFO("..:: Test TIMS frame init begin ::..");
  //   OboPsiMod test;

  TimsFrameBase frame(1, 671);

  MzRange mz_range(1200.0001, PrecisionFactory::getPpmInstance(10));

  SECTION("Test 1")
  {
    double temperature_correction =
      77.0 * (25.4933665127396 - 25.59978165276) +
      (-3.7) * (26.2222755503081 - 27.6311281556638);
    temperature_correction = (double)1.0 + (temperature_correction / 1.0e6);


    frame.setMzCalibration(25.59978165276,
                           27.6311281556638,
                           0.2,
                           24864.0,
                           313.577620892277,
                           157424.07710945,
                           0.000338743021989553,
                           0.0,
                           0.0,

                           25.4933665127396,
                           26.2222755503081,
                           77.0,
                           -3.7);
    frame.setTimsCalibration(2,
                             1,
                             670,
                             207.775676931964,
                             59.2526676368822,
                             33.0,
                             1,
                             0.0209889001473149,
                             131.440113097798,
                             12.9712317295887,
                             2558.71692505931);
    frame.setTime(2402.64305686123);
    frame.setMsMsType(0);
    quint32 index =
      frame.getMzCalibrationInterfaceSPtr().get()->getTofIndexFromMz(
        mz_range.getMz());
    qDebug() << "index=" << index;
    double mz =
      frame.getMzCalibrationInterfaceSPtr().get()->getMzFromTofIndex(index);
    qDebug() << "mz=" << QString::number(mz, 'g', 10);

    REQUIRE(mz_range.contains(mz));

    // 313792
    mz = frame.getMzCalibrationInterfaceSPtr().get()->getMzFromTofIndex(
      (quint32)313793);
    qDebug() << " 313793 => mz=" << QString::number(mz, 'g', 10);
    mz = frame.getMzCalibrationInterfaceSPtr().get()->getMzFromTofIndex(
      (quint32)313792);

    REQUIRE(QString::number(mz, 'g', 10) == "1200.002299");
    qDebug() << " 313792 => mz=" << QString::number(mz, 'g', 10);
    mz = frame.getMzCalibrationInterfaceSPtr().get()->getMzFromTofIndex(
      (quint32)313791);
    qDebug() << " 313791 => mz=" << QString::number(mz, 'g', 10);


    double one_over_k0 = frame.getOneOverK0Transformation(400);
    qDebug() << " 400 => one_over_k0=" << QString::number(one_over_k0, 'g', 10);
    std::size_t scan_num = frame.getScanNumFromOneOverK0(one_over_k0);

    REQUIRE(scan_num == 400);
    cout << std::endl << "..:: Test 1 OK ::.." << std::endl;
  }

  SECTION("Test 2")
  {
    cout << std::endl
         << "..:: second test, new calibration parameters ::.." << std::endl;


    frame.setMzCalibration(25.3072302808429,
                           25.3072302808429,
                           0.2,
                           24864.0,
                           313.577620892277,
                           157424.07710945,
                           0.000338743021989553,
                           0.0,
                           0.0,

                           25.4933665127396,
                           26.2222755503081,
                           77.0,
                           -3.7);
    /*
          q.value(2).toDouble(),  // MzCalibration.DigitizerTimebase
          q.value(3).toDouble(),  // MzCalibration.DigitizerDelay
          q.value(4).toDouble(),  // MzCalibration.C0
          q.value(5).toDouble(),  // MzCalibration.C1
          q.value(6).toDouble(),  // MzCalibration.C2
          q.value(7).toDouble()); // MzCalibration.C3
          */

    frame.setTimsCalibration(2,
                             1,
                             1537,
                             179.152532325778,
                             90.4208212951646,
                             33.0,
                             1,
                             0.009221,
                             131.053614,
                             9.656516,
                             2095.24199);
    frame.setTime(1.7950832);
    frame.setMsMsType(0);

    std::size_t index =
      frame.getMzCalibrationInterfaceSPtr().get()->getTofIndexFromMz(
        mz_range.getMz());
    qDebug() << "index=" << index;
    double mz =
      frame.getMzCalibrationInterfaceSPtr().get()->getMzFromTofIndex(index);
    qDebug() << "mz=" << QString::number(mz, 'g', 10);

    REQUIRE(mz_range.contains(mz));

    // 313792
    mz = frame.getMzCalibrationInterfaceSPtr().get()->getMzFromTofIndex(
      (quint32)313793);
    qDebug() << " 313793 => mz=" << QString::number(mz, 'g', 10);
    mz = frame.getMzCalibrationInterfaceSPtr().get()->getMzFromTofIndex(
      (quint32)313792);
    qDebug() << " 313792 => mz=" << QString::number(mz, 'g', 10);
    mz = frame.getMzCalibrationInterfaceSPtr().get()->getMzFromTofIndex(
      (quint32)313791);
    qDebug() << " 313791 => mz=" << QString::number(mz, 'g', 10);


    double one_over_k0 = frame.getOneOverK0Transformation(400);
    qDebug() << " 400 => one_over_k0=" << QString::number(one_over_k0, 'g', 10);
    std::size_t scan_num = frame.getScanNumFromOneOverK0(one_over_k0);

    REQUIRE(scan_num == 400);


    mz = frame.getMzCalibrationInterfaceSPtr().get()->getMzFromTofIndex(
      (quint32)375176);
    qDebug() << " 375176 => mz=" << QString::number(mz, 'g', 10);


    REQUIRE_FALSE(mz < 50.0);
    cout << std::endl << "..:: Test 2 OK ::.." << std::endl;
  }


#if USEPAPPSOTREE == 1
  SECTION("Test TIMS TDF parsing issue #61")
  {
    INFO("Test case ERROR reading TIMS frame 58581");

    pappso::MsFileAccessor accessor(
      "/gorgone/pappso/fichiers_fabricants/Bruker/tims_doc/tdf-sdk/"
      "example_data/200ngHeLaPASEF_2min_compressed.d/"
      "analysis.tdf",
      "a1");


    accessor.setPreferedFileReaderType(pappso::MzFormat::brukerTims,
                                       pappso::FileReaderType::tims_ms2);


    pappso::MsRunReaderSPtr p_msreader =
      accessor.msRunReaderSp(accessor.getMsRunIds().front());

    REQUIRE(p_msreader != nullptr);

    REQUIRE(accessor.getFileReaderType() == pappso::FileReaderType::tims_ms2);

    pappso::TimsMsRunReaderMs2 *tims2_reader =
      dynamic_cast<pappso::TimsMsRunReaderMs2 *>(p_msreader.get());
    REQUIRE(tims2_reader != nullptr);
    if(tims2_reader != nullptr)
      {
        tims2_reader->setMs2BuiltinCentroid(true);
        tims2_reader->setMs2FilterCstSPtr(std::make_shared<FilterSuiteString>(
          FilterSuiteString("chargeDeconvolution|0.02dalton")));
      }
    pappso::QualifiedMassSpectrum mass_spectrum;
    REQUIRE_NOTHROW(mass_spectrum = tims2_reader->qualifiedMassSpectrum(5001));


    /*
     * 23:   ..:: Test TIMS frame init begin ::..
23:   Test case ERROR reading TIMS frame 58581
23:   ERROR reading TIMS frame 60575 TIMS binary file
/home/langella/data1/bruker/ 23:
5-18-2021_1_robert_28_mic02-std_1354.d/analysis.tdf_bin:  decompressed_size2 23:
== ZSTD_CONTENTSIZE_ERROR, frame_length=265254592

*/
    REQUIRE_NOTHROW(mass_spectrum = tims2_reader->qualifiedMassSpectrum(6001));
    REQUIRE_NOTHROW(mass_spectrum = tims2_reader->qualifiedMassSpectrum(6003));
    REQUIRE_NOTHROW(mass_spectrum = tims2_reader->qualifiedMassSpectrum(6005));
    REQUIRE_NOTHROW(mass_spectrum = tims2_reader->qualifiedMassSpectrum(6007));
    REQUIRE_THROWS_AS(mass_spectrum =
                        tims2_reader->qualifiedMassSpectrum(35460),
                      pappso::ExceptionNotFound);
  }


  SECTION("Test TIMS TDF parsing")
  {
    INFO("Test case pappso::FileReaderType::tims_ms2 start");

    pappso::MsFileAccessor accessor(
      "/gorgone/pappso/versions_logiciels_pappso/masschroq/donnees/"
      "PXD014777_maxquant_timstof/"
      "20180809_120min_200ms_WEHI25_brute20k_timsON_100ng_HYE124B_Slot1-8_1_"
      "894.d/analysis.tdf",
      "a1");
    /*
    pappso::MsFileAccessor accessor(
      "/gorgone/pappso/fichiers_fabricants/Bruker/tims_doc/tdf-sdk/"
      "example_data/200ngHeLaPASEF_2min_compressed.d/"
      "analysis.tdf",
      "a1");
*/
    /*
        pappso::MsFileAccessor accessor(
          "/gorgone/pappso/fichiers_fabricants/Bruker/tims_doc/tdf-sdk/"
          "example_data/"
          "200ngHeLaPASEF_2min_compressed.d/analysis.tdf",
          "a1");
    */
    /*
        pappso::MsFileAccessor accessor(
          "/data/test_tdf_quality/2-3-2021_1_HeLa10ng_871.d/analysis.tdf",
       "a1");
    */

    accessor.setPreferedFileReaderType(pappso::MzFormat::brukerTims,
                                       pappso::FileReaderType::tims);


    pappso::MsRunReaderSPtr p_msreader_tims_ms1 =
      accessor.msRunReaderSp(accessor.getMsRunIds().front());

    pappso::TimsMsRunReader *tims1_reader =
      dynamic_cast<pappso::TimsMsRunReader *>(p_msreader_tims_ms1.get());

    REQUIRE_FALSE(p_msreader_tims_ms1.get() == nullptr);
    REQUIRE_FALSE(tims1_reader == nullptr);

    pappso::TimsDataSp timsdata_sp = tims1_reader->getTimsDataSPtr();

    REQUIRE_NOTHROW(timsdata_sp.get()->getRawMsBySpectrumIndex(0));
    REQUIRE_NOTHROW(timsdata_sp.get()->getRawMsBySpectrumIndex(1));
    REQUIRE_NOTHROW(p_msreader_tims_ms1.get()->massSpectrumCstSPtr(0));
    // REQUIRE_NOTHROW(p_msreader_tims_ms1.get()->massSpectrumCstSPtr(1000));

    for(std::size_t i = 0; i < 1000; i++)
      {
        qDebug()
          << " size(" << (i) << ")="
          << p_msreader_tims_ms1.get()->massSpectrumCstSPtr(i).get()->size();
      }
    p_msreader_tims_ms1.get()->massSpectrumCstSPtr(53);
    p_msreader_tims_ms1.get()->massSpectrumCstSPtr(5000);
    // timsdata_sp.get()->getRawMsBySpectrumIndex(8207);

    REQUIRE_NOTHROW(p_msreader_tims_ms1.get()->massSpectrumCstSPtr(8207));

    // 8206, frameId=9 scanNum=910 ERROR in
    // MzCalibrationModel1::getMzFromTofIndex m[0].y!= 0
    REQUIRE_NOTHROW(p_msreader_tims_ms1.get()->massSpectrumCstSPtr(8206));

    // scan_num=899 spectrum_index=899
    REQUIRE_NOTHROW(p_msreader_tims_ms1.get()->massSpectrumCstSPtr(899));


    accessor.setPreferedFileReaderType(pappso::MzFormat::brukerTims,
                                       pappso::FileReaderType::tims_ms2);


    pappso::MsRunReaderSPtr p_msreader =
      accessor.msRunReaderSp(accessor.getMsRunIds().front());

    REQUIRE(p_msreader != nullptr);

    REQUIRE(accessor.getFileReaderType() == pappso::FileReaderType::tims_ms2);

    pappso::TimsMsRunReaderMs2 *tims2_reader =
      dynamic_cast<pappso::TimsMsRunReaderMs2 *>(p_msreader.get());
    REQUIRE(tims2_reader != nullptr);
    if(tims2_reader != nullptr)
      {
        tims2_reader->setMs2BuiltinCentroid(true);
        tims2_reader->setMs2FilterCstSPtr(std::make_shared<FilterSuiteString>(
          FilterSuiteString("chargeDeconvolution|0.02dalton")));
      }

    pappso::QualifiedMassSpectrum mass_spectrum =
      tims2_reader->qualifiedMassSpectrum(7001);

    INFO("mass_spectrum.getMsLevel()=" << mass_spectrum.getMsLevel());
    INFO("mass_spectrum.getPrecursorMz()=" << mass_spectrum.getPrecursorMz());
    INFO("mass_spectrum.getMassSpectrumId().getSpectrumIndex()="
         << mass_spectrum.getMassSpectrumId().getSpectrumIndex());

    INFO(mass_spectrum.getMassSpectrumSPtr()->xValues().at(0));
    REQUIRE_FALSE(mass_spectrum.getMassSpectrumCstSPtr().get()->back().x <
                  40.0);


    INFO("Test case pappso::FileReaderType::tims start");

    accessor.setPreferedFileReaderType(pappso::MzFormat::brukerTims,
                                       pappso::FileReaderType::tims);


    class SpectrumCollectionHandler : public SpectrumCollectionHandlerInterface
    {
      public:
      virtual ~SpectrumCollectionHandler(){};
      virtual void
      setQualifiedMassSpectrum(const QualifiedMassSpectrum &spectrum) override
      {
        m_count++;
        if((m_count % 1000) == 0)
          {
            WARN("count "
                 << m_count << " "
                 << spectrum.getMassSpectrumId().getNativeId().toStdString()
                 << " MSlevel=" << spectrum.getMsLevel());

            if(spectrum.getMsLevel() == 1)
              {
                REQUIRE_FALSE(spectrum.getMassSpectrumCstSPtr() == nullptr);
              }
            if(spectrum.getMassSpectrumCstSPtr() != nullptr)
              {
                WARN(" size=" << spectrum.size());
              }
            //<< " size=" << spectrum.toString().toStdString());
          }
      };
      virtual bool
      needPeakList() const override
      {
        return false;
      };

      std::size_t m_count = 0;
    };

    SpectrumCollectionHandler dummy_handler;

    Catch::Timer t;
    t.start();

    WARN("reading all spectrum collection of file "
         << accessor.getFileName().toStdString());
    dummy_handler.setNeedMsLevelPeakList(1, false);
    dummy_handler.setNeedMsLevelPeakList(2, false);
    // tims1_reader->readSpectrumCollectionByMsLevel(dummy_handler, 1);

    auto s = t.getElapsedSeconds();

    WARN("reading time in second : " << s);


    // git hash 597d6a68062a45d5e3ccaaa8398598a62dc69043 reading time in second
    // : 1447.15

    // git hash 7dc0806a4ca1fd0e92da97dcc44ac9b44c381d9f reading time in second
    // : 1445.65
    // if we disable binary data reading : reading time in second : 1220.77 =>
    // there is somehow room for performance enhancements

    // git hash 26c8053d4fcfae15b98c75b715d79cd615bf42e0 reading time in second
    // : 1440.25


    // git hash 2d0d2a4edcfcef583bc60bd5b14e6b0df1505a02 reading time in second
    // : 1447.3
    // => avoiding sql query is not really efficient
  }
  /*
cout << std::endl
  << mass_spectrum.getMassSpectrumCstSPtr()
       .get()
       ->toString()
       .toStdString()
       .c_str()
  << std::endl;
*/
  /*
   *
22:
/home/langella/developpement/git/pappsomspp/src/pappsomspp/vendors/tims/timsframebase.cpp@513,
pappso::TimsFrameBase::getTraceFromCumulatedScansBuiltinCentroid():
375176 22:
/home/langella/developpement/git/pappsomspp/src/pappsomspp/vendors/tims/timsframebase.cpp@518,
pappso::TimsFrameBase::getTraceFromCumulatedScansBuiltinCentroid():
99944.2 22:
/home/langella/developpement/git/pappsomspp/src/pappsomspp/vendors/tims/timsframebase.cpp@253,
pappso::TimsFrameBase::getMzFromTof(): m.length()= 3 22:
/home/langella/developpement/git/pappsomspp/src/pappsomspp/vendors/tims/timsframebase.cpp@520,
pappso::TimsFrameBase::getTraceFromCumulatedScansBuiltinCentroid(): 41.3832

polynome :
-101811 2523.58 -0.002221 313.267
=>  m1= 42.058

*/

  /*
22:
/home/langella/developpement/git/pappsomspp/src/pappsomspp/vendors/tims/timsframebase.cpp@513,
pappso::TimsFrameBase::getTraceFromCumulatedScansBuiltinCentroid():
374144 22:
/home/langella/developpement/git/pappsomspp/src/pappsomspp/vendors/tims/timsframebase.cpp@518,
pappso::TimsFrameBase::getTraceFromCumulatedScansBuiltinCentroid():
99692.8 22:
/home/langella/developpement/git/pappsomspp/src/pappsomspp/vendors/tims/timsframebase.cpp@192,
pappso::TimsFrameBase::getMzFromTof(): 0 22:
/home/langella/developpement/git/pappsomspp/src/pappsomspp/vendors/tims/timsframebase.cpp@253,
pappso::TimsFrameBase::getMzFromTof(): m.length()= 2 22:
/home/langella/developpement/git/pappsomspp/src/pappsomspp/vendors/tims/timsframebase.cpp@520,
pappso::TimsFrameBase::getTraceFromCumulatedScansBuiltinCentroid():
1554.74

polynome :
-100327 2520.37 0.000338744
=> m1= 1584.54

*/


#elif USEPAPPSOTREE == 1

  cout << std::endl
       << "..:: NO test TIMS TIC chromatogram extraction ::.." << std::endl;

#endif
}
