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


// ./tests/catch2-only-benchmarks [proteincode] -s --benchmark-samples 5


#define CATCH_CONFIG_ENABLE_BENCHMARKING

#include <catch2/catch_test_macros.hpp>
#include <catch2/benchmark/catch_benchmark.hpp>

#include <QDebug>
#include <pappsomspp/exception/exceptionnotfound.h>
#include <pappsomspp/exception/exceptionoutofrange.h>
#include <pappsomspp/protein/protein.h>
#include <pappsomspp/protein/proteinintegercode.h>
#include <pappsomspp/massspectrum/qualifiedmassspectrum.h>
#include <pappsomspp/processing/filters/filterresample.h>
#include <pappsomspp/processing/filters/filterpass.h>
#include <pappsomspp/processing/filters/filterchargedeconvolution.h>
#include <pappsomspp/processing/filters/filterpeakdelta.h>
#include <pappsomspp/amino_acid/aastringcodemassmatching.h>
#include <pappsomspp/fasta/fastareader.h>
#include "../common.h"
#include "tests/config.h"
#include "../proteincode/proteincode_lib.h"

TEST_CASE("proteincode test suite.", "[proteincode]")
{
  // Set the debugging message formatting pattern.
  qSetMessagePattern(QString("%{file}@%{line}, %{function}(): %{message}"));


  SECTION("..:: scan spectrum on fasta file ::..", "[proteincodes]")
  {
    std::cout << std::endl
              << "..:: Test Fasta big file indexer ::.." << std::endl;
    QFile file2(QString(CMAKE_SOURCE_DIR)
                  .append("/tests/data/fasta/Genome_Z_mays_5a.small.fasta"));

    FastaProteinArrayHandler protein_handler;
    pappso::FastaReader reader(protein_handler);
    reader.parse(file2);

    // compute spectrum code :

    pappso::MassSpectrum spectrum = readMgf(
      QString(CMAKE_SOURCE_DIR).append("/tests/data/peaklist_15046.mgf"));


    pappso::FilterResampleKeepGreater(160).filter(spectrum);
    pappso::FilterChargeDeconvolution(
      pappso::PrecisionFactory::getDaltonInstance(0.02))
      .filter(spectrum);
    //.applyCutOff(150).takeNmostIntense(100).applyDynamicRange(100);
    pappso::FilterGreatestY(100).filter(spectrum);

    pappso::FilterPeakDelta filter_peak_delta;
    filter_peak_delta.filter(spectrum);

    pappso::FilterGreatestY(200).filter(spectrum);
    std::vector<double> mass_list = spectrum.xValues();


    // ok spectrum code

    pappso::AaCode aa_code;
    aa_code.addAaModification('C',
                              pappso::AaModification::getInstance("MOD:00397"));
    pappso::AaStringCodec aa_codec(aa_code);

    pappso::ProteinSp max_protein;
    double max_score = 0;

    //


    pappso::AaStringCodeMassMatching aaMatching(
      aa_code, 7, pappso::PrecisionFactory::getDaltonInstance(0.01));

    std::vector<uint32_t> code_list_from_spectrum =
      aaMatching.getAaCodeFromMassList(mass_list);

    std::vector<pappso::ProteinIntegerCode> arr_codedProtein;

    REQUIRE(protein_handler.getProteinArray().size() == 3041);

    BENCHMARK("fasta protein coder")
    {
      /* mode debug 2325604b33c648c7621fc637f4838e0654a9a2b3
       *  --benchmark-samples 5
       * fasta protein coder                              5 1     14.6394 s
                                       2.92579 s     2.89503 s     2.97303 s
                                      44.3713 ms    17.6264 ms     63.129 ms
       */
      for(auto &protein : protein_handler.getProteinArray())
        {
          pappso::ProteinSp protein_sp = protein.makeProteinSp();

          qDebug() << protein_sp.get()->getAccession();
          // pappso::ProteinIntegerCode protein_code(protein_sp, aa_codec, 5);

          arr_codedProtein.push_back({protein_sp, aa_codec, 5});
        }
    };


    // std::vector<uint32_t> code_list = code_list_from_spectrum;

    std::sort(code_list_from_spectrum.begin(), code_list_from_spectrum.end());
    code_list_from_spectrum.erase(std::unique(code_list_from_spectrum.begin(),
                                              code_list_from_spectrum.end()),
                                  code_list_from_spectrum.end());


    BENCHMARK("protein convolution")
    {
      for(auto &protein_code : arr_codedProtein)
        {
          /* mode debug cd443161fbbb3cd2f15c7f92cb94b6cef9cb0c0f
           *  --benchmark-samples 5
           * protein convolution                              5 1     1.28755 m
                                       15.9592 s     15.6614 s     16.2533 s
                                      356.477 ms    196.799 ms     477.38 ms

           */
          auto vec_score = protein_code.convolution(code_list_from_spectrum);
          double score   = *std::max(vec_score.begin(), vec_score.end());

          if(score > max_score)
            {
              max_score   = score;
              max_protein = protein_code.getProteinSp();
            }
        }
    };
    REQUIRE(max_protein.get()->getAccession().toStdString() ==
            "GRMZM2G151344_P01"); //GRMZM2G083841_P01
  }
}
