#include <numeric>
#include <limits>
#include <vector>
#include <map>
#include <cmath>

#include <QDebug>
#include <QFile>

#if 0
// For debugging purposes.
#include <QFile>
#endif

#include "massspectrumcombiner.h"
#include "../../types.h"
#include "../../utils.h"
#include "../../pappsoexception.h"
#include "../../exception/exceptionoutofrange.h"
#include "../../exception/exceptionnotpossible.h"


namespace pappso
{


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


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


MassSpectrumCombiner::MassSpectrumCombiner(std::vector<pappso_double> bins,
                                           int decimalPlaces)
  : MassDataCombinerInterface(decimalPlaces)
{
  m_bins.assign(bins.begin(), bins.end());
}


MassSpectrumCombiner::MassSpectrumCombiner(const MassSpectrumCombiner &other)
  : MassDataCombinerInterface(other.m_decimalPlaces)
{
  m_bins.assign(other.m_bins.begin(), other.m_bins.end());

  // QString debug_string = QString(
  //"Number of bins: %1\n"
  //"First bins: %2 %3 %4 -- Last bins: %5 %6 %7\n")
  //.arg(m_bins.size())
  //.arg(m_bins[0], 0, 'f', 6)
  //.arg(m_bins[1], 0, 'f', 6)
  //.arg(m_bins[2], 0, 'f', 6)
  //.arg(m_bins[m_bins.size() - 3], 0, 'f', 6)
  //.arg(m_bins[m_bins.size() - 2], 0, 'f', 6)
  //.arg(m_bins[m_bins.size() - 1], 0, 'f', 6);

  // qDebug().noquote() << debug_string;
}


MassSpectrumCombiner::MassSpectrumCombiner(MassSpectrumCombinerCstSPtr other)
  : MassDataCombinerInterface(other->m_decimalPlaces)
{
  m_bins.assign(other->m_bins.begin(), other->m_bins.end());
}


//! Destruct the instance.
MassSpectrumCombiner::~MassSpectrumCombiner()
{
  m_bins.clear();
}


void
MassSpectrumCombiner::setBins(std::vector<pappso_double> bins)
{
  m_bins.assign(bins.begin(), bins.end());

  // QString debug_string = QString(
  //"Number of bins: %1\n"
  //"First bins: %2 %3 %4 -- Last bins: %5 %6 %7\n")
  //.arg(m_bins.size())
  //.arg(m_bins[0], 0, 'f', 6)
  //.arg(m_bins[1], 0, 'f', 6)
  //.arg(m_bins[2], 0, 'f', 6)
  //.arg(m_bins[m_bins.size() - 3], 0, 'f', 6)
  //.arg(m_bins[m_bins.size() - 2], 0, 'f', 6)
  //.arg(m_bins[m_bins.size() - 1], 0, 'f', 6);

  // qDebug().noquote() << debug_string;
}


const std::vector<pappso_double> &
MassSpectrumCombiner::getBins() const
{
  return m_bins;
}


std::size_t
MassSpectrumCombiner::binCount() const
{
  return m_bins.size();
}


//! Find the bin that will contain \p mz.
std::vector<pappso_double>::iterator
MassSpectrumCombiner::findBin(pappso_double mz)
{
  return std::find_if(m_bins.begin(), m_bins.end(), [mz](pappso_double bin) {
    return (mz <= bin);
  });
}


QString
MassSpectrumCombiner::binsAsString() const
{
  QString text;

  for(auto &bin : m_bins)
    text += QString("%1\n").arg(bin, 0, 'f', 6);

  text += "\n";

  return text;
}

} // namespace pappso
