/**
 * \file pappsomspp/filers/filterlocalmaximum.cpp
 * \date 24/09/2019
 * \author Olivier Langella
 * \brief filter to select local maximum in a spectrum
 * inspired from the proteowizard library "LocalMaximumPeakDetector"
 */

/*******************************************************************************
 * Copyright (c) 2019 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/>.
 *
 ******************************************************************************/


#include "filterlocalmaximum.h"
#include "../../trace/trace.h"
using namespace pappso;

FilterLocalMaximum::FilterLocalMaximum(std::size_t half_window_size)
  : m_halfWindowSize(half_window_size)
{
}

FilterLocalMaximum::FilterLocalMaximum(const FilterLocalMaximum &other)
  : m_halfWindowSize(other.m_halfWindowSize)
{
}

FilterLocalMaximum::~FilterLocalMaximum()
{
}

Trace &
FilterLocalMaximum::filter(Trace &data_points) const
{

  if(m_halfWindowSize == 0)
    return data_points;
  Trace new_trace;
  auto it = data_points.begin();

  auto itend = data_points.end() - m_halfWindowSize - 1; // no filter at the end of signal
  // new_trace.reserve(data_points.size());

  while((it != data_points.end()) &&
        (std::distance(data_points.begin(), it) < (int)m_halfWindowSize))
    {
      // no filter at the begining of the signal
      it++;
    }
  while(it != itend)
    {
      auto itwend = it + m_halfWindowSize + 1;
      auto itw    = maxYDataPoint(it - m_halfWindowSize, it + 1);
      if(itw == it)
        {
          itw = maxYDataPoint(it, itwend);
          if(itw == it)
            {
              new_trace.push_back({it->x, it->y});
            }
        }

      it++;
    }

  data_points = std::move(new_trace);
  return data_points;
}

std::size_t
FilterLocalMaximum::getHalfWindowSize() const
{
  return m_halfWindowSize;
}
