/**
 * \file src/gui/xic_view/xicworkerthread.cpp
 * \date 12/1/2018
 * \author Olivier Langella
 * \brief XIC worker
 */
/*******************************************************************************
 * Copyright (c) 2018 Olivier Langella <olivier.langella@u-psud.fr>.
 *
 * This file is part of i2MassChroQ.
 *
 *     i2MassChroQ 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.
 *
 *     i2MassChroQ 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 i2MassChroQ.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contributors:
 *     Olivier Langella <olivier.langella@u-psud.fr> - initial API and
 *implementation
 ******************************************************************************/

#include <tuple>
#include "xicworkerthread.h"
#include <pappsomspp/core/peptide/peptidenaturalisotopelist.h>
#include <pappsomspp/core/pappsoexception.h>
#include <pappsomspp/core/exception/exceptionnotfound.h>
#include <pappsomspp/core/msrun/private/timsmsrunreaderms2.h>
#include <pappsomspp/core/processing/uimonitor/uimonitorvoid.h>
#include <pappsomspp/core/processing/filters/filterpass.h>
#include <QDebug>


XicWorkerThread::XicWorkerThread(XicBox *parent [[maybe_unused]])
{
}
XicWorkerThread::~XicWorkerThread()
{
}
void
XicWorkerThread::doXicLoad(MsRunSp p_msrun,
                           std::vector<pappso::XicCoordSPtr> xic_coord_list,
                           MasschroqFileParametersSp masschroq_params_sp)
{

  try
    {
      pappso::MsRunXicExtractorInterfaceSp extractor =
        p_msrun.get()->getMsRunXicExtractorInterfaceSp();
      if(extractor != nullptr)
        {
          qDebug();
          extractor.get()->setXicExtractMethod(
            masschroq_params_sp.get()
              ->m_quantificationMethod.getXicExtractMethod());

          /*
                    pappso::FilterInterfaceCstSPtr filter_sp =
                      std::make_shared<const
             pappso::FilterQuantileBasedRemoveY>(0.1);
                    extractor.get()->setPostExtractionTraceFilterCstSPtr(filter_sp);
          */
          if(masschroq_params_sp.get()
               ->m_quantificationMethod.getFilterSuiteStringSPtr()
               .get() != nullptr)
            {
              pappso::FilterInterfaceCstSPtr filter_sp =
                masschroq_params_sp.get()
                  ->m_quantificationMethod.getXicFilter();
              extractor.get()->setPostExtractionTraceFilterCstSPtr(filter_sp);
            }
          qDebug();
          pappso::UiMonitorVoid monitor;
          extractor.get()->extractXicCoordSPtrList(monitor, xic_coord_list);

          qDebug();
        }
      emit xicLoaded(xic_coord_list);
    }
  catch(pappso::PappsoException &error)
    {
      emit operationFailed(tr("Error extracting XIC for MSrun %1 %2 %3:\n%4")
                             .arg(__FILE__)
                             .arg(__FUNCTION__)
                             .arg(p_msrun->getFileName())
                             .arg(error.qwhat()));
    }

  catch(std::exception &std_error)
    {
      emit operationFailed(
        tr("Error extracting XIC for MSrun %1 %2 %3 std_error:\n%4")
          .arg(__FILE__)
          .arg(__FUNCTION__)
          .arg(p_msrun->getFileName())
          .arg(std_error.what()));
    }
}


void
XicWorkerThread::doComputeIsotopeMassList(pappso::PeptideSp peptide_sp,
                                          unsigned int charge,
                                          pappso::PrecisionPtr precision,
                                          double minimum_isotope_pattern_ratio)
{
  qDebug() << precision->toString();
  std::vector<pappso::PeptideNaturalIsotopeAverageSp> isotope_mass_list;

  try
    {
      // compute isotope masses :
      if(peptide_sp != nullptr)
        {
          pappso::PeptideNaturalIsotopeList isotope_list(peptide_sp);
          isotope_mass_list = isotope_list.getByIntensityRatio(
            charge, precision, minimum_isotope_pattern_ratio);

          qDebug();
          std::sort(
            isotope_mass_list.begin(),
            isotope_mass_list.end(),
            [](const pappso::PeptideNaturalIsotopeAverageSp &m,
               const pappso::PeptideNaturalIsotopeAverageSp &n) -> bool {
              unsigned int mn(m.get()->getIsotopeNumber()),
                nn(n.get()->getIsotopeNumber());
              unsigned int mr(m.get()->getIsotopeRank()),
                nr(n.get()->getIsotopeRank());
              return (std::tie(mn, mr) < std::tie(nn, nr));
            });
          qDebug();
          emit isotopeMassListComputed(isotope_mass_list);
        }
    }
  catch(pappso::PappsoException &error)
    {
      emit operationFailed(tr("Error in %1 %2 :\n%3")
                             .arg(__FILE__)
                             .arg(__FUNCTION__)
                             .arg(error.qwhat()));
    }
  catch(std::exception &std_error)
    {
      emit operationFailed(tr("Error in %1 %2 std_error:\n%3")
                             .arg(__FILE__)
                             .arg(__FUNCTION__)
                             .arg(std_error.what()));
    }
}
