/////////////////////// StdLib includes
#include <numeric>
#include <limits>
#include <vector>
#include <map>
#include <cmath>
#include <iostream>
#include <iomanip>


/////////////////////// Qt includes
#include <QDebug>
#include <QFile>
#include <QThread>
#if 0
// For debugging purposes.
#include <QFile>
#endif


/////////////////////// Local includes
#include "massspectrumpluscombiner.h"
#include "../../types.h"
#include "../../utils.h"
#include "../../pappsoexception.h"
#include "../../exception/exceptionoutofrange.h"
#include "../../exception/exceptionnotpossible.h"


namespace pappso
{


//! Construct an uninitialized instance.
MassSpectrumPlusCombiner::MassSpectrumPlusCombiner()
{
}


MassSpectrumPlusCombiner::MassSpectrumPlusCombiner(int decimal_places)
  : MassSpectrumCombiner(decimal_places)
{
}


MassSpectrumPlusCombiner::MassSpectrumPlusCombiner(
  const MassSpectrumPlusCombiner &other)
  : MassSpectrumCombiner(other)

{
  // qDebug() << __FILE__ << " @ " << __LINE__ << __FUNCTION__ << "()";
}


MassSpectrumPlusCombiner::MassSpectrumPlusCombiner(
  MassSpectrumPlusCombinerCstSPtr other)
  : MassSpectrumCombiner(other)

{
  // qDebug() << __FILE__ << " @ " << __LINE__ << __FUNCTION__ << "()";
}


//! Destruct the instance.
MassSpectrumPlusCombiner::~MassSpectrumPlusCombiner()
{
}


MapTrace &
MassSpectrumPlusCombiner::combineNoFilteringStep(MapTrace &map_trace,
                                                 const Trace &trace) const
{
  //qDebug();

  if(!trace.size())
    {
      // qDebug() << "Thread:" << QThread::currentThreadId()
      //<< "Returning right away because trace is empty.";
      return map_trace;
    }

  // We will need to only use these iterator variables if we do not want to
  // loose consistency.

  using TraceIter            = std::vector<DataPoint>::const_iterator;
  TraceIter trace_iter_begin = trace.begin();
  TraceIter trace_iter       = trace_iter_begin;
  TraceIter trace_iter_end   = trace.end();

  // The destination map trace will be filled-in with the result of the
  // combination.

  // Sanity check:
  if(!m_bins.size())
    throw(ExceptionNotPossible("The bin vector cannot be empty."));

  using BinIter = std::vector<pappso_double>::const_iterator;

  BinIter bin_iter     = m_bins.begin();
  BinIter bin_end_iter = m_bins.end();

  // qDebug() << "initial bins iter at a distance of:"
  //<< std::distance(m_bins.begin(), bin_iter)
  //<< "bins distance:" << std::distance(m_bins.begin(), m_bins.end())
  //<< "bins size:" << m_bins.size() << "first bin:" << m_bins.front()
  //<< "last bin:" << m_bins.back();

  // Iterate in the vector of bins and for each bin check if there are matching
  // data points in the trace.

  pappso_double current_bin = 0;

  pappso_double trace_x = 0;
  pappso_double trace_y = 0;

  // Lower bound returns an iterator pointing to the first element in the
  // range [first, last) that is not less than (i.e. greater or equal to)
  // value, or last if no such element is found.

  auto bin_iter_for_mz = lower_bound(bin_iter, bin_end_iter, trace_iter->x);

  if(bin_iter_for_mz != bin_end_iter)
    {
      if(bin_iter_for_mz != m_bins.begin())
        bin_iter = --bin_iter_for_mz;
    }
  else
    throw(ExceptionNotPossible("The bin vector must match the mz value."));

  while(bin_iter != bin_end_iter)
    {
      current_bin = *bin_iter;

      // qDebug() << "Current bin:" << QString("%1").arg(current_bin, 0, 'f',
      // 15)
      //<< "at a distance of:"
      //<< std::distance(m_bins.begin(), bin_iter);

      // For the current bin, we start by instantiating a new DataPoint. By
      // essence, each bin will have at most one corresponding DataPoint.

      DataPoint new_data_point;

      // Do not set the y value to 0 so that we can actually test if the
      // data point is valid later on (try not to push back y=0 data
      // points).
      new_data_point.x = current_bin;

      // Now perform a loop over the data points in the mass spectrum.

      // qDebug() << "trace_iter:" << trace_iter->toString()
      //<< "data point distance:"
      //<< std::distance(trace_iter_begin, trace_iter);

      while(trace_iter != trace_iter_end)
        {

          bool trace_matched = false;

          // If trace is not to the end and the y value is not 0
          // apply the shift, perform the rounding and check if the obtained
          // x value is in the current bin, that is if it is less or equal
          // to the current bin.

          // qDebug() << "Thread:" << QThread::currentThreadId();
          // qDebug() << "trace_iter:" << trace_iter->toString()
          //<< "data point distance:"
          //<< std::distance(trace_iter_begin, trace_iter);

          // if(!Utils::almostEqual(trace_iter->y, 0.0, 10))
          if(trace_iter->y)
            {
              trace_x = trace_iter->x;
              trace_y = trace_iter->y;

              // trace_x is the m/z value that we need to combine,
              // so make sure we check if there is a mz shift to apply.

              // if(m_mzIntegrationParams.m_applyMzShift)
              // trace_x += m_mzIntegrationParams.m_mzShift;

              // Now apply the rounding (if any).
              if(m_decimalPlaces != -1)
                trace_x = Utils::roundToDecimals(trace_x, m_decimalPlaces);

              if(trace_x <= current_bin)
                {

                  // qDebug() << "Matched, increment trace_iter";
                  new_data_point.y += trace_y;

                  // Let's record that we matched.
                  trace_matched = true;

                  // Because we matched, we can step-up with the
                  // iterator.
                  ++trace_iter;
                }
              // else
              //{
              // We did have a non-0 y value, but that did not
              // match. So we do not step-up with the iterator.
              //}
            }
          // End of
          // if(trace_iter->y)
          else
            {
              // We iterated into a y=0 data point, so just skip it. Let
              // the below code think that we have matched the point and
              // iterate one step up.

              // qDebug() << "The y value is almost equal to 0, increment the "
              //"trace iter but do nothing else.";

              trace_matched = true;
              ++trace_iter;
            }
          // At this point, check if none of them matched.

          if(!trace_matched)
            {
              // None of the first and trace mass spectra data
              // points were found to match the current bin. All we
              // have to do is go to the next bin. We break and the
              // bin vector iterator will be incremented.

              // However, if we had a valid new data point, that
              // data point needs to be pushed back in the new mass
              // spectrum.

              if(new_data_point.isValid())
                {

                  // We need to check if that bin value is present already in
                  // the map_trace object passed as parameter.

                  std::pair<std::map<pappso_double, pappso_double>::iterator,
                            bool>
                    result =
                      map_trace.insert(std::pair<pappso_double, pappso_double>(
                        new_data_point.x, new_data_point.y));

                  if(!result.second)
                    {
                      // The key already existed! The item was not inserted. We
                      // need to update the value.

                      result.first->second += new_data_point.y;

                      // qDebug() << "Incremented the data point in the map
                      // trace.";
                    }
                  // else
                  //{
                  // qDebug()
                  //<< "Inserted a new data point into the map trace.";
                  //}
                }

              // We need to break this loop! That will increment the
              // bin iterator.

              break;
            }
        }
      // End of
      // while(1)

      // Each time we get here, that means that we have consumed all
      // the mass spectra data points that matched the current bin.
      // So go to the next bin.

      if(trace_iter == trace_iter_end)
        {

          // Make sure a last check is done in case one data point was
          // cooking...

          if(new_data_point.isValid())
            {

              std::pair<std::map<pappso_double, pappso_double>::iterator, bool>
                result =
                  map_trace.insert(std::pair<pappso_double, pappso_double>(
                    new_data_point.x, new_data_point.y));

              if(!result.second)
                {
                  result.first->second += new_data_point.y;
                }
            }

          // Now truly exit the loops...
          break;
        }

      ++bin_iter;
    }
  // End of
  // while(bin_iter != bin_end_iter)

  // qDebug() << __FILE__ << "@" << __LINE__ << __FUNCTION__ << " ()"
  //<< "The combination result mass spectrum being returned has TIC:"
  //<< new_trace.sumY();

  return map_trace;
}


} // namespace pappso

