/**
 * \file pappsomspp/xicextractor/msrunxicextractor.cpp
 * \date 07/05/2018
 * \author Olivier Langella
 * \brief base interface to build XICs on an MsRun file
 */

/*******************************************************************************
 * Copyright (c) 2018 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/>.
 *
 * Contributors:
 *     Olivier Langella <Olivier.Langella@u-psud.fr> - initial API and
 *implementation
 ******************************************************************************/

#include "msrunxicextractorinterface.h"
#include <QThreadPool>
#include <QtConcurrent>
#include "../processing/uimonitor/uimonitorvoid.h"

namespace pappso
{


MsRunXicExtractorInterface::MsRunXicExtractorInterface(
  MsRunReaderSPtr &msrun_reader)
  : msp_msrun_reader(msrun_reader)
{
}


MsRunXicExtractorInterface::MsRunXicExtractorInterface(
  const MsRunXicExtractorInterface &other)
  : msp_msrun_reader(other.msp_msrun_reader)
{
  m_xicExtractMethod = other.m_xicExtractMethod;
}

MsRunXicExtractorInterface::~MsRunXicExtractorInterface()
{
}

void
MsRunXicExtractorInterface::setXicExtractMethod(XicExtractMethod method)
{
  m_xicExtractMethod = method;
}

void
MsRunXicExtractorInterface::setRetentionTimeAroundTarget(
  double range_in_seconds)
{
  m_retentionTimeAroundTarget = range_in_seconds;
}

const MsRunIdCstSPtr &
MsRunXicExtractorInterface::getMsRunId() const
{
  return msp_msrun_reader.get()->getMsRunId();
}

const MsRunReaderSPtr &
MsRunXicExtractorInterface::getMsRunReaderSPtr() const
{
  return msp_msrun_reader;
}

void
MsRunXicExtractorInterface::setPostExtractionTraceFilterCstSPtr(
  pappso::FilterInterfaceCstSPtr &filter)
{
  mcsp_postExtractionTraceFilter = filter;
}


void
MsRunXicExtractorInterface::extractXicCoordSPtrListParallelized(
  UiMonitorInterface &monitor, std::vector<XicCoordSPtr> &xic_coord_list)
{
  qDebug();
  // get the number of available threads :
  int number_of_threads = QThreadPool::globalInstance()->maxThreadCount();

  if(number_of_threads == 1)
    {
      extractXicCoordSPtrList(monitor, xic_coord_list);
    }
  else
    {
      monitor.setStatus(QObject::tr("parallelized extraction of %1 XICs")
                          .arg(xic_coord_list.size()));

      std::size_t chunck_size = xic_coord_list.size() / number_of_threads;
      chunck_size += 1;
      if(chunck_size < 1000)
        chunck_size = 1000;

      struct parallelExtractChunck
      {
        std::vector<XicCoordSPtr>::iterator it_xic_coord_begin;
        std::vector<XicCoordSPtr>::iterator it_xic_coord_end;
      };

      std::vector<parallelExtractChunck> chunck_list;
      qDebug();
      for(auto it = xic_coord_list.begin(); it != xic_coord_list.end();)
        {
          qDebug() << "chunck_size=" << chunck_size;
          parallelExtractChunck chunck;
          chunck.it_xic_coord_begin = it;
          for(std::size_t i = 0; i < chunck_size && it != xic_coord_list.end();
              i++)
            {
              it++;
            }
          chunck.it_xic_coord_end = it;
          chunck_list.push_back(chunck);
        }
      qDebug();
      auto self = this;

      qDebug();
      std::function<std::size_t(const parallelExtractChunck &)> extractChunck =
        [self](const parallelExtractChunck &extract_chunck) {
          qDebug();
          UiMonitorVoid monitor;
          self->protectedExtractXicCoordSPtrList(
            monitor,
            extract_chunck.it_xic_coord_begin,
            extract_chunck.it_xic_coord_end);
          self->postExtractionProcess(monitor,
                                      extract_chunck.it_xic_coord_begin,
                                      extract_chunck.it_xic_coord_end);
          qDebug();
          return 1;
        };
      qDebug();
      monitor.setTotalSteps(chunck_list.size());
      UiMonitorInterface *monitorRef = &monitor;
      std::function<void(std::size_t & result, const std::size_t &value)>
        monitorExtract2 =
          [monitorRef](std::size_t &result [[maybe_unused]],
                       const std::size_t &value
                       [[maybe_unused]]) { monitorRef->count(); };
      qDebug();

      QFuture<std::size_t> res =
        QtConcurrent::mappedReduced<std::size_t>(chunck_list.begin(),
                                                 chunck_list.end(),
                                                 extractChunck,
                                                 monitorExtract2,
                                                 QtConcurrent::UnorderedReduce);
      qDebug();

      /*
        QFuture<std::size_t> res =
          QtConcurrent::mapped(chunck_list.begin(), chunck_list.end(),
        extractChunck);
      */
      res.waitForFinished();
      monitor.setTotalSteps(0);
    }
}

void
MsRunXicExtractorInterface::extractXicCoordSPtrList(
  UiMonitorInterface &monitor, std::vector<XicCoordSPtr> &xic_coord_list)
{

  monitor.setStatus(
    QObject::tr("extracting %1 XICs").arg(xic_coord_list.size()));
  monitor.setTotalSteps(xic_coord_list.size());
  protectedExtractXicCoordSPtrList(
    monitor, xic_coord_list.begin(), xic_coord_list.end());
  monitor.setTotalSteps(0);
  postExtractionProcess(monitor, xic_coord_list.begin(), xic_coord_list.end());
}

void
MsRunXicExtractorInterface::postExtractionProcess(
  UiMonitorInterface &monitor,
  std::vector<XicCoordSPtr>::iterator it_xic_coord_list_begin,
  std::vector<XicCoordSPtr>::iterator it_xic_coord_list_end)
{

  if(mcsp_postExtractionTraceFilter != nullptr)
    {
      monitor.setStatus(
        QObject::tr("filtering %1 XICs")
          .arg(std::distance(it_xic_coord_list_begin, it_xic_coord_list_end)));
      for(auto it = it_xic_coord_list_begin; it != it_xic_coord_list_end; it++)
        {
          mcsp_postExtractionTraceFilter.get()->filter(
            *(it->get()->xicSptr.get()));
        }
    }
}


} // namespace pappso
