/////////////////////// 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)

{
}


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

{
}


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


MassSpectrumPlusCombiner &
MassSpectrumPlusCombiner::operator=(const MassSpectrumPlusCombiner &other)
{
  if(this == &other)
    return *this;

  m_decimalPlaces = other.m_decimalPlaces;

  m_bins.assign(other.m_bins.begin(), other.m_bins.end());

  return *this;
}


// We get a trace as parameter that this combiner needs to combine to the
// map_trace we also get as parameter. This combiner is for a mass spectrum, and
// thus it needs to have been configured to hold a vector of m/z values that are
// bins into which DataPoints from trace are combined into map_trace. It is the
// bins that drive the the traversal of trace. For each bin, check if there is
// (or are, if bins are big) data points in the trace that fit in it.

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

  // If there is no single point in the trace we need to combine into the
  // map_trace, then there is nothing to do.
  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_mz = 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_mz = *bin_iter;

      // std::cout << std::setprecision(10) << "current bin: " << current_bin_mz
      //<< std::endl;

      // qDebug() << "Current bin:"
      //<< QString("%1").arg(current_bin_mz, 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_mz;

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

      // qDebug() << "Start looping in the trace to check if its DataPoint.x "
      //"value matches that of the current bin."
      //<< "trace_iter:" << trace_iter->toString()
      //<< "data point distance:"
      //<< std::distance(trace_iter_begin, trace_iter);

      while(trace_iter != trace_iter_end)
        {
          // std::cout << std::setprecision(10)
          //<< "trace data point being iterated into: " << trace_iter->x
          //<< " - " << trace_iter->y << std::endl;

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

          trace_x = trace_iter->x;
          trace_y = trace_iter->y;

          if(trace_y)
            {

              // FIXME: unbelievable behaviour: when building in release mode
              // this code, under i386 (but not x86_64), this code fails if the
              // following%S statement is missing. There are a variety of
              // variants that work, the common denominator being that trace_x
              // has to be output along with a string.

              // std::cout << std::setprecision(10)
              //<< "iterated trace point: " << trace_x << " - "
              //<< trace_y << std::endl;

              // For this reason I had to deactivate the related tests
              // for i386 in tests/test_massspectrumcombiner.cpp

              // 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_mz)
                {

                  // std::cout
                  //<< std::setprecision(10)
                  //<< "Matched, because trace point.x is <= the current "
                  //"bin; increment trace_iter"
                  //<< std::endl;

                  new_data_point.y += trace_y;

                  // std::cout << std::setprecision(10)
                  //<< "After incrementation of the intensity: "
                  //<< new_data_point.y << std::endl;

                  // 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
            {
              // std::cout << std::setprecision(10)
              //<< "itered trace point intensity is 0: " << trace_x
              //<< " - " << trace_y << std::endl;


              // 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(trace_iter != trace_iter_end)

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


MapTrace &
MassSpectrumPlusCombiner::combine(MapTrace &map_trace_out,
                                  const MapTrace &map_trace_in) const
{
  // qDebug();

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

  Trace trace(map_trace_in);

  return combine(map_trace_out, trace);
}


} // namespace pappso
