//
// 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/proteincode/catch2-only-proteincode [proteincode] -s

// ./tests/proteincode/catch2-only-proteincode [spectrumcode] -s


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

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


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


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


  SECTION("..:: scan spectrum on fasta file ::..", "[spectrumcode]")
  {
    // compute spectrum code :
    REQUIRE(aa_code.getMass(aa_code.getAaCode('R')) == Catch::Approx(156.101111));
    // 175.11

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


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

    spectrum.append({MASSOXYGEN + MPROTIUM, spectrum.maxIntensityDataPoint().y * 0.5});
    spectrum.append({MPROTIUM, spectrum.maxIntensityDataPoint().y * 0.5});

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

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

    // REQUIRE(mass_list.size() == 150);

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

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


    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());

    // AIADGSLLDLLR

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

#if USEPAPPSOTREE == 1

  std::cout << std::endl << "..:: Test Fasta big file indexer ::.." << std::endl;
  QFile file2("/gorgone/pappso/moulon/database/Genome_Z_mays_5a.fasta");

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


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

  writeJsonAaCode("aacode.json", aa_code);

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

  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});
    }

  SECTION("..:: scan spectrum on fasta file ::..", "[proteincodefasta]")
  {
    // compute spectrum code :

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


    writeJsonTrace("peaklist_15046.json", spectrum);


    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::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::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());

    std::vector<double> convolution_score;

    std::size_t i_protein_code = 0;
    std::size_t i              = 0;
    for(auto &coded_protein : arr_codedProtein)
      {
        pappso::ProteinSp protein_sp = coded_protein.getProteinSp();

        qDebug() << protein_sp.get()->getAccession();
        std::vector<double> vec_score = coded_protein.convolution(code_list_from_spectrum);
        auto it_score                 = std::max_element(vec_score.begin(), vec_score.end());

        // double score = std::accumulate(it_score - 2, it_score + 5, 0);

        if(it_score != vec_score.end())
          {
            // std::cout << protein_sp.get()->getAccession().toStdString() << "
            // "
            //         << score << std::endl;
            double score = std::accumulate(it_score - 2, it_score + 5, 0);
            if(score > max_score)
              {
                max_score         = score;
                max_protein       = protein_sp;
                convolution_score = vec_score;
                i_protein_code    = i;

                std::cout << protein_sp.get()->getAccession().toStdString() << " " << max_score
                          << std::endl;
              }
          }
        i++;
      }


    writeProteinConvolutionScore(
      "best_fit_peaklist_15046.ods", *(max_protein.get()), nullptr, convolution_score);

    pappso::ProteinPresenceAbsenceMatrix presence_absence_matrix;
    presence_absence_matrix.fillMatrix(arr_codedProtein.at(i_protein_code),
                                       code_list_from_spectrum);

    writeProteinConvolutionScoreJson("best_fit_peaklist_15046.json",
                                     *(max_protein.get()),
                                     arr_codedProtein.at(i_protein_code),
                                     &presence_absence_matrix,
                                     convolution_score);
    REQUIRE(max_protein.get()->getAccession().toStdString() ==
            "GRMZM2G083841_P01"); // //GRMZM2G083841_P01
  }

  SECTION("..:: scan spectrum on fasta file scan_15968.mgf ::..", "[proteincodefasta]")
  {
    // compute spectrum code :

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


    pappso::FilterResampleKeepGreater(200).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(500).filter(spectrum);
    std::vector<double> mass_list = spectrum.xValues();


    // ok spectrum 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::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());

    std::vector<double> convolution_score;


    for(auto &coded_protein : arr_codedProtein)
      {
        pappso::ProteinSp protein_sp = coded_protein.getProteinSp();

        // qDebug() << protein_sp.get()->getAccession();
        std::vector<double> vec_score = coded_protein.convolution(code_list_from_spectrum);

        auto it_score = std::max_element(vec_score.begin(), vec_score.end());

        // double score = std::accumulate(it_score - 2, it_score + 5, 0);

        if(it_score != vec_score.end())
          {
            // std::cout << protein_sp.get()->getAccession().toStdString() << "
            // "
            //         << score << std::endl;
            double score = std::accumulate(it_score - 2, it_score + 5, 0);

            if(protein_sp.get()->getAccession() == "GRMZM5G815453_P01")
              {

                std::cout << protein_sp.get()->getAccession().toStdString() << " " << score
                          << std::endl;
              }
            /*
                        if(score > 6000)
                          {

                            std::cout <<
               protein_sp.get()->getAccession().toStdString()
                                      << " " << score << std::endl;
                          }
            */
            if(score > max_score)
              {
                max_score         = score;
                max_protein       = protein_sp;
                convolution_score = vec_score;

                std::cout << protein_sp.get()->getAccession().toStdString() << " " << max_score
                          << std::endl;
              }
          }
      }


    writeProteinConvolutionScore(
      "best_fit_scan_15968.ods", *(max_protein.get()), nullptr, convolution_score);
    REQUIRE(max_protein.get()->getAccession().toStdString() ==
            "GRMZM5G815453_P01"); // //GRMZM5G815453_P01 EITLGFVDLLR
  }
#endif
}
